標籤:
Java 類載入過程:(以A.class為例)
1. 定位A.class類,並調用findLoaderClass(string)判斷這個類是否已經存在
2. 先執行父類中static成員變數與static方法塊
3. 再執行子類中static成員變數與static方法塊
4. 接著執行父類中非static成員變數、非static方法塊和建構函式
5. 最後執行子類中非static成員變數、非static方法塊和建構函式
注意:建構函式是最後執行的。
下面用測試過的代碼輸入來說明:
(1)類中沒有成員變數時
1 public class Test1 { 2 static{ 3 System.out.println(5); 4 } 5 6 public Test1() { 7 System.out.println(6); 8 } 9 {10 System.out.println(7);11 }12 }13 14 public class Test extends Test1 { 15 static{16 System.out.println(1);17 }18 {19 System.out.println(2);20 } 21 public Test() {22 System.out.println(3);23 }24 {25 System.out.println(4);26 } 27 public static void main(String[] args) {28 Test test=new Test();29 }30 }
輸出:5 1 7 6 2 4 3
(2)有其他執行個體化對象時
1 public class Test1 { 2 static Test2 test22=new Test2("static_father_test2"); 3 Test2 test2=new Test2("father_test2"); 4 static{ 5 System.out.println(5); 6 } 7 8 public Test1() { 9 System.out.println(6);10 }11 {12 System.out.println(7);13 }14 }15 16 public class Test2 {17 public Test2(String str) {18 System.out.println("test2:"+str);19 }20 }21 public class Test extends Test1 { 22 static Test2 test22=new Test2("static_test22"); 23 Test2 test2=new Test2("test2"); 24 static{25 System.out.println(1);26 }27 {28 System.out.println(2);29 }30 31 public Test() {32 System.out.println(3);33 }34 {35 System.out.println(4);36 } 37 public static void main(String[] args) {38 Test test=new Test();39 }40 }
輸出列印:
test2:static_father_test2
5
test2:static_test22
1
test2:father_test2
7
6
test2:test2
2
4
3
劍指offer-Java類載入過程