public class Test1 {
public static int k = 0;
public static Test1 t1 = new Test1("t1");
public static Test1 t2 = new Test1("t2");
public static int i = print("i");
public static int n = 99;
public int j = print("j");
{ print("構造塊"); }
static { print("靜態塊"); }
public Test1(String str) { System.out.println((++k) + " : " + str + " i=" + i + " n=" + n); ++i; ++n; }
public static int print(String str) { System.out.println((++k) + " : " + str + " i=" + i + " n=" + n); ++n; return ++i; }
public static void main(String[] args) { Test1 t = new Test1("init"); }
}
1 : t1 i=0 n=0
2 : t2 i=1 n=1
3 : i i=2 n=2
4 : 靜態塊 i=3 n=3
5 : init i=4 n=99
6 : j i=5 n=100
7 : 構造塊 i=6 n=101
| 步驟 | 執行代碼 | 關鍵狀態變化 |
|---|---|---|
| 1 | static int k = 0 | k=0 |
| 2 | static Test1 t1 = new Test1("t1") | 調用構造器 → 打印第1行 → 此時 i、n 尚未初始化,默認 0 |
| 3 | static Test1 t2 = new Test1("t2") | 調用構造器 → 打印第2行 → i=1, n=1 |
| 4 | static int i = print("i") | 調用 print → 打印第3行 → i=2, n=2 |
| 5 | static int n = 99 | n=99(覆蓋前值) |
| 6 | static { print("靜態塊") } | 打印第4行 → n=3 (print 內 ++n) |
| 7 | main 中 new Test1("init") | 實例化:實例字段 j=print("j")→第5行;實例塊→第6行;構造器體→第7行 |
i=0, n=0)。print 方法修改了靜態變量 i、n,影響後續初始化。「靜態按順序,實例按順序,靜態先於實例,父類先於子類」。遇到構造器中訪問靜態字段,**務必確認該字段是否已初始化完成**。