問題代碼
public class Child extends Parent {
public Child(String name, int age, School school) {
this("George", 10, school); // 行 19
}
public Child(String name, int age) {
this(name, age, new School()); // 行 18
}
// 無參構造器未顯式調用 super()
}
規則解析
- 子類構造器**第一行**若無
this(...) 或 super(...),編譯器**隱式插入 super()** 調用父類無參構造器。
- 若父類**沒有無參構造器**(只定義了帶參構造器),隱式
super() 會編譯失敗,必須顯式調用 super(參數)。
- 代碼中第 18 行
this(name, age, new School()) 調用三參構造器,第 19 行 this("George", 10, school) 同理,**構造器鏈最終會到達三參構造器**,由該構造器負責調用 super(...)(或隱式 super())。
- 因此第 18-19 行**不直接調用
super() 是合法的**,因為它們委託給另一構造器,由最終構造器完成父類初始化。
關鍵點
- 構造器鏈:
this(...) 必須是第一條語句,且鏈條終點必須調用 super(...)(顯式或隱式)。
- 父類無無參構造器時,子類**每條構造器鏈的終點**必須顯式
super(參數)。