使用兩個類,一個父類,一個子類
父類代碼:
1 public class Parent { 2 public static int i = 10; 3 private int j = 15; 4 5 static { 6 System.out.println("parent 靜態代碼塊,無靜態變量"); 7 } 8 9 static { 10 i = i + 100; 11 System.out.println("parent 靜態代碼塊,有靜態變量,i=" + i); 12 } 13 14 { 15 System.out.println("parent 代碼塊,無靜態變量"); 16 } 17 18 { 19 j = j + 200; 20 System.out.println("parent 代碼塊,有靜態變量,j=" + j); 21 } 22 23 public Parent() { 24 System.out.println("parent 構造方法"); 25 } 26 27 }
子類代碼:
1 public class Child extends Parent { 2 public static int m = 26; 3 private int n = 37; 4 5 static { 6 System.out.println("child 靜態代碼塊,無靜態變量"); 7 } 8 9 static { 10 m = m + 300; 11 System.out.println("child 靜態代碼塊,有靜態變量,m=" + m); 12 } 13 14 { 15 System.out.println("child 代碼塊,無靜態變量"); 16 } 17 18 { 19 n = n + 400; 20 System.out.println("child 代碼塊,有靜態變量, n=" + n); 21 } 22 23 public Child(){ 24 System.out.println("child 構造方法"); 25 } 26 27 public static void main(String[] args) { 28 Child child = new Child(); 29 } 30 }
執行結果:
parent 靜態代碼塊,無靜態變量
parent 靜態代碼塊,有靜態變量,i=110
child 靜態代碼塊,無靜態變量
child 靜態代碼塊,有靜態變量,m=326
parent 代碼塊,無靜態變量
parent 代碼塊,有靜態變量,j=215
parent 構造方法
child 代碼塊,無靜態變量
child 代碼塊,有靜態變量, n=437
child 構造方法
結論:
1. 若存在繼承關系,而且父類和子類中都存在靜態代碼塊、靜態變量、構造代碼塊、構造方法
2. 先是父類靜態代碼塊和靜態變量,靜態代碼塊和靜態變量的初始化順序 是誰在前誰先加載
3. 再是子類靜態代碼塊和靜態變量,靜態代碼塊和靜態變量的初始化順序 是誰在前誰先加載
4. 再是父類構造代碼塊,父類構造方法
5. 再是子類構造代碼塊,父類構造方法