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所澄清的那樣。
添加回答
舉報