在創建新物件時,所有繼承而來的建構子都會被依序調用,這一過程稱為建構子鏈。例如,Hippo 物件同時是 Animal 和 Object,創建 Hippo 時,必須先完成 Animal 和 Object 的部分初始化。
public class Animal {
public Animal() {
System.out.println("Make a animal");
}
}
public class Hippo extends Animal {
public Hippo() {
// super(); 預設隱式調用父類無參建構子
System.out.println("Make a Hippo");
}
}
public class TestHippo {
public static void main(String[] args) {
System.out.println("Starting...");
Hippo hippo = new Hippo();
}
}
輸出結果將依序為:
Starting... Make a animal Make a Hippo
super(...) 語句(必須為建構子第一行)。class Fu {
int x = 30;
Fu() { System.out.println(x); }
Fu(int x) { System.out.println(x); }
}
class Zi extends Fu {
Zi() {
// super(); // 預設調用父類無參建構子
// super(4); // 指定調用父類帶參建構子
this(20); // 調用本類帶參建構子
System.out.println("zi ..." + x);
}
Zi(int x) {
System.out.println("zi..." + x);
}
}
public class Single {
public static void main(String[] args) {
Zi z = new Zi();
}
}
由於 Zi() 中調用了 this(20),會先執行 Zi(int x),而該建構子隱式調用 super(),因此父類無參建構子先執行,輸出 30;隨後執行 Zi(int x) 輸出 zi...20;最後返回 Zi() 輸出 zi ...30。
關鍵點:this() 和 super() 不能同時出現在建構子中,且必須為第一條語句。