为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容708150 2022-08-03 15:33:12
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编译器给出错误我无法理解为什么需要这个默认构造函数?
查看完整描述

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所澄清的那样。


查看完整回答
反对 回复 2022-08-03
  • 1 回答
  • 0 关注
  • 167 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号