子類構造方法可以同時調用 super(...) 和其他方法,但有嚴格語法限制:
super(...) 必須放在構造方法第一行。this(...)、普通方法)必須在 super(...) 之後。super(...),編譯器默認插入 super()(無參構造),仍佔第一行位置。class Father {
Father(String msg) { System.out.println("Father: " + msg); }
void fatherMethod() { System.out.println("Father method"); }
}
class Son extends Father {
Son(String msg) {
super(msg); // 必須第一行
fatherMethod(); // 允許:調用父類普通方法
this.sonMethod(); // 允許:調用自身方法
System.out.println("Son constructed");
}
void sonMethod() { System.out.println("Son method"); }
}
// 錯誤 1:super 不在第一行
Son() {
System.out.println("before super");
super("msg"); // Compile error: call to super must be first statement
}
// 錯誤 2:this() 與 super() 不能共存
Son() {
this("default"); // 若寫 this(),則不能再寫 super(),二者互斥
super("msg");
}
private 或 final 方法,或使用工廠模式/建造者模式。