以下 java 代码有什么问题?
What's wrong with the following java code?
我在编译时遇到一些参数错误。不知道这是怎么回事。
我原以为输出是 bj。因为 Class a 没有默认构造函数,所以在编译时默认构造函数将由 JVM 创建。剩下的输出将是 bj。我错过了什么吗?
class a
{
a(String b)
{
System.out.println("this is a");
}
}
class b extends a
{
b()
{
System.out.println("b");
}
}
class c extends b
{
c(String j)
{
System.out.println(j);
}
public static void main(String...k)
{
new c("J");
}
}
错误如下图:
javac construct.java
construct.java:12: error: constructor a in class a cannot be applied to given ty
pes;
{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
since Class a doesn't have default constructor so at compilation time default constructor would be created by JVM
只有在您没有定义自定义构造函数时才会创建默认构造函数。
您的 IDE 应该在 b()
声明中向您显示以下消息:
There is no default constructor available in 'package.a'
当您尝试实例化 b
时,它对 super()
进行了隐式调用,但只找到 a(String b)
而不是 a()
。如错误消息所述,a(String b)
需要 String
但没有参数。
解决方案是创建无参数 a()
构造函数或在 class b
构造函数中调用 a(String b)
构造函数。
class b extends a
{
b()
{
super(""); // call to class a constructor passing some string as argument
System.out.println("b");
}
}
按照惯例,您应该以大写字母命名 Java 类
执行new C("J");
时,会调用class C
的构造函数。但由于 class C
正在扩展 class B
,JVM 将添加
C(String j)
{
super(); //added by JVM - calls the constructor of super class
System.out.println("j");
}
所以 class b 的构造函数被调用,因为它也在扩展 class A
。
B()
{
super(); //added by JVM
System.out.println("b");
}
现在问题来了。由于 JVM 将在其隐式调用中添加默认构造函数。但是没有用无参数定义的构造函数。这就是你收到错误的原因。您可以在构造函数 B 中添加 super("");
来解决错误,或者创建一个不带参数的构造函数。
我在编译时遇到一些参数错误。不知道这是怎么回事。
我原以为输出是 bj。因为 Class a 没有默认构造函数,所以在编译时默认构造函数将由 JVM 创建。剩下的输出将是 bj。我错过了什么吗?
class a
{
a(String b)
{
System.out.println("this is a");
}
}
class b extends a
{
b()
{
System.out.println("b");
}
}
class c extends b
{
c(String j)
{
System.out.println(j);
}
public static void main(String...k)
{
new c("J");
}
}
错误如下图:
javac construct.java
construct.java:12: error: constructor a in class a cannot be applied to given ty
pes;
{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
since Class a doesn't have default constructor so at compilation time default constructor would be created by JVM
只有在您没有定义自定义构造函数时才会创建默认构造函数。
您的 IDE 应该在 b()
声明中向您显示以下消息:
There is no default constructor available in 'package.a'
当您尝试实例化 b
时,它对 super()
进行了隐式调用,但只找到 a(String b)
而不是 a()
。如错误消息所述,a(String b)
需要 String
但没有参数。
解决方案是创建无参数 a()
构造函数或在 class b
构造函数中调用 a(String b)
构造函数。
class b extends a
{
b()
{
super(""); // call to class a constructor passing some string as argument
System.out.println("b");
}
}
按照惯例,您应该以大写字母命名 Java 类
执行new C("J");
时,会调用class C
的构造函数。但由于 class C
正在扩展 class B
,JVM 将添加
C(String j)
{
super(); //added by JVM - calls the constructor of super class
System.out.println("j");
}
所以 class b 的构造函数被调用,因为它也在扩展 class A
。
B()
{
super(); //added by JVM
System.out.println("b");
}
现在问题来了。由于 JVM 将在其隐式调用中添加默认构造函数。但是没有用无参数定义的构造函数。这就是你收到错误的原因。您可以在构造函数 B 中添加 super("");
来解决错误,或者创建一个不带参数的构造函数。