| 特性 | 實例構造方法 | 靜態初始化塊 |
|---|---|---|
| 關鍵字 | `public ClassName() {}` | `static {}` |
| 執行觸發 | 每次 `new ClassName()` | 類**首次主動使用**時(加載/初始化階段) |
| 執行次數 | 每個實例一次 | **整個 JVM 生命週期僅一次**(每類加載器) |
| 初始化目標 | 實例字段(非靜態) | 靜態字段(static) |
| 可訪問成員 | 實例 + 靜態 | 僅靜態(無 this) |
| 異常處理 | 可拋出異常阻止對象創建 | 只能拋運行時異常,否則導致 `ExceptionInInitializerError` |
class Student {
static { System.out.println("1. 靜態塊"); } // ① 類加載時
{ System.out.println("2. 實例塊"); } // ② new 時,構造器前
public Student() { System.out.println("3. 構造方法"); } // ③ new 時
public Student(String name) {
this(); System.out.println("4. 重載構造"); // ④ this() 調用
}
}
public class Test {
public static void main(String[] args) {
System.out.println("--- 首次 new ---");
new Student(); // 輸出 1,2,3
System.out.println("--- 二次 new ---");
new Student("Alice"); // 輸出 2,3,4 (靜態塊不再執行)
}
}
不觸發:訪問常量(`static final` 編譯期常量)、聲明變量 `Student s;`、創建數組 `new Student[10]`。
Java 無 `static public Student()` 語法。靜態初始化**只能通過 `static {}` 塊**完成。若見到「靜態構造函數」說法,指的就是靜態初始化塊。