最近研究了下Java的类加载顺序,发现个奇怪的事情:
如果只有一个类(此类名为Super),会先给静态变量赋值,然后加载该类的静态块、实例块、最后调用构造器创建实例。
如果该类有一个子类,情况如下:
1 (Super)first static block!! str:Hello,spring 2 3 (Super)second static block!! str:Hello,spring 4 5 (SubClass)first static block!! a:3 6 7 (SubClass)second static block!! 8 9 (Super)Instance block!! object:object 10 11 Super's constructor!! str:Hello,spring 12 13 14 (SubClass)Instance block!! 15 16 SubClass's constructor!! object:java.lang.Object@5cb0d902 17 18 19 (Super)Instance block!! object:object 20 21 Super's constructor!! str:Hello,spring 22 23 24 (SubClass)Instance block!! 25 26 SubClass's constructor!! object:java.lang.Object@69663380
超类和子类的实例块和构造器会被加载2次,此处甚为不解!!
望各位能指教一二!!
超类代码:
1 public class Super { 2 3 private static String str = "Hello,spring"; 4 private Object object = "object"; 5 6 // 第1个静态块 7 static { 8 9 System.out.println("\n (Super)first static block!! str:" + str); 10 11 } 12 13 // 实例块 14 { 15 16 System.out.println("\n (Super)Instance block!! object:" + object); 17 } 18 19 // 第2个静态块 20 static { 21 22 System.out.println("\n (Super)second static block!! str:" + str); 23 } 24 25 public Super() { 26 27 System.out.println("\nSuper's constructor!! str:" + str + "\n"); 28 } 29 }
子类代码:
1 public class SubClass extends Super { 2 3 private static Integer a = 3; 4 private Object object; 5 6 // 第1个静态块 7 static { 8 9 System.out.println("\n (SubClass)first static block!! a:" + a); 10 11 } 12 13 // 实例块 14 { 15 16 System.out.println("\n (SubClass)Instance block!! "); 17 } 18 19 // 第2个静态块 20 static { 21 22 System.out.println("\n (SubClass)second static block!!"); 23 } 24 25 public SubClass(){ 26 27 this.object = new Object(); 28 System.out.println("\nSubClass's constructor!! object:" + this.object + "\n"); 29 30 } 31 32 public Object getObject() { 33 return object; 34 } 35 36 public void setObject(Object object) { 37 this.object = object; 38 } 39 40 }