1 回答

TA贡献1784条经验 获得超2个赞
您需要指定用于创建超类的构造函数(如果该类没有不带参数的构造函数(默认的构造函数) *
构造函数中的第一个语句是对 的调用,除非您使用任何参数指示对 this 或 super 的显式调用。该调用由 java 在编译时间注入。因此,它在 Y 类中寻找非 args 构造函数。super()
super()
请参阅文档:
注: 如果构造函数未显式调用超类构造函数,Java 编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,您将收到编译时错误。对象确实有这样的构造函数,所以如果对象是唯一的超类,那就没有问题了。
在实践中,编译器将预处理您的代码并生成如下内容:
class X{
X(){
super(); // Injected by compiler
System.out.println("Inside X()");
}
X(int x){
super(); // Injected by compiler
System.out.println("Inside X(int)");
}
}
class Y extends X{
Y(String s){
super(); // Injected by compiler
System.out.println("Inside Y(String)");
}
Y(int y){
super(1000);
System.out.println("Inside Y(int)");
}
}
class Z extends Y{
Z(){
super(); // Injected by compiler
System.out.println("Inside Z()");
}
Z(int z){
super(100);
System.out.println("Inside Z(int)");
}
}
public class Program{
public static void main(String args[]){
Z z=new Z(10);
}
}
然后它将继续编译它,但是如您所见,Z非参数构造函数尝试引用Y非参数构造函数,这不存在。
*正如Carlos Heuberger所澄清的那样。
添加回答
举报