猿问

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

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);

    }

}

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


程序.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编译器给出错误我无法理解为什么需要这个默认构造函数?


慕容708150
浏览 168回答 1
1回答

一只斗牛犬

您需要指定用于创建超类的构造函数(如果该类没有不带参数的构造函数(默认的构造函数) *构造函数中的第一个语句是对 的调用,除非您使用任何参数指示对 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所澄清的那样。
随时随地看视频慕课网APP

相关分类

Java
我要回答