super():子類建構子首行若無明確 super(...),編譯器自動插入無參數 super()。public class Grapha {
public Grapha(String name) { System.out.println("Grapha(String)"); }
// 無無參數建構子
}
class Father extends Grapha {
public Father() { } // 編譯錯誤:implicit super constructor Grapha() is undefined
public Father(String name) { } // 編譯錯誤:同上
}
修正方式:在 Father 每個建構子首行加上 super("someName"),或在 Grapha 補上無參數建構子。
| 模式 | 私有建構子用途 | 關鍵點 |
|---|---|---|
| Singleton (單例) | 阻止外部 new,靜態工廠方法回傳唯一實例 | 雙重檢查鎖定、Enum 實作 (最簡潔、防序列化破壞) |
| Enum 類別 | 語言層面保證單例、防反射攻擊 | public enum Singleton { INSTANCE; } |
| 工廠方法 / 靜態工廠 | 封裝複雜建構邏輯、回傳快取/子類實例 | Boolean.valueOf(true) 回傳快取常量 |
| 不可變類別 | 配合 final 欄位、無 setter,建構子一次性初始化 | String、LocalDate、BigInteger 等 |
| Utility 類別 | 純靜態方法,不需實例化 | Collections、Math、Arrays |
public final class Singleton {
private static volatile Singleton INSTANCE;
private Singleton() { /* 複雜初始化 */ }
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) INSTANCE = new Singleton();
}
}
return INSTANCE;
}
}
this 引用)。final 類別 + final 欄位 + 私有建構子/靜態工廠。@SuppressWarnings("unused") 標註刻意保留的私有建構子,避免靜態分析誤報。