亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

下面是代碼片段和錯誤消息,為什么編譯器要求這個默認構造函數?

下面是代碼片段和錯誤消息,為什么編譯器要求這個默認構造函數?

慕容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 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號