以下是代码片段和错误消息,为什么编译器要求此默认构造函数


class X{
    X(){
        System.out.println("Inside X()");
    }
    X(int x){
        System.out.println("Inside X(int)");
    }
}
class Y extends X{
    Y(String s){
        System.out.println("Inside Y(String)");
    }
    Y(int y){
        super(1000);
        System.out.println("Inside Y(int)");
    }
}
class Z extends Y{
    Z(){
        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);
    }
}

上面的代码在编译时给出以下错误: -

program.java:23:错误:找不到适合y的构造函数(无参数)

Z(){
   ^
constructor Y.Y(String) is not applicable
  (actual and formal argument lists differ in length)
constructor Y.Y(int) is not applicable
  (actual and formal argument lists differ in length)

1错误

当我们调用参数化构造函数时,默认构造函数的用途是什么,Java编译器给出了错误,我无法理解为什么需要此默认构造函数?

如果没有参数(默认一个) *

,则需要指定用于创建超级类的构造函数。

您的构造函数中的第一个语句是对super()的呼叫,除非您指定对此或具有任何参数的明确调用。Java在Compilación时间内注入了super()调用。因此,它正在寻找Y类的非args构造函数。

请参阅文档:

注意:如果构造函数未明确调用超类 构造函数,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非Argument构造函数尝试引用不存在的非Argument构造器。

*作为Carlos Heuberger澄清。

相关内容

最新更新