通过一个父类和子类代码来说明:
1 public class ClassLoaderOrder { 2 public static void main(String[] args) { 3 /** 4 * 输出: 5 * 父类的静态方法2 6 * 我是父类静态初始化块 7 * 父类类的静态方法 8 * 在类被加载的时候,会先初始化类中静态成员变量 也就是t 9 * t调用了静态方法2 所以会先输出 "父类的静态方法2" 10 * 然后初始化类的静态代码块 "我是父类静态初始化块" 11 * 最后调用parentStaticMethod(),打印"父类类的静态方法" 12 */ 13 //Parent.parentStaticMethod(); 14 /** 15 * 输出: 16 * 父类的静态方法2 17 * 我是父类静态初始化块 18 * 子类静态初始化块 19 * 20 * 我是父类非静态块 21 * 我是父类构造函数 22 * 23 * 子类的静态方法 24 * 子类非静态初始化块 25 * 子类的构造方法 26 * 27 * 子类被new时: 28 * 先初始化父类静态变量(按顺序) 29 * 初始化父类和子类的静态块 30 * 初始化父类非静态块,父类构造函数 31 * 子类静态变量 32 * 初始化子类非静态块,子类构造函数 33 * 34 */ 35 Child child = new Child(); 36 } 37 38 } 39 40 class Parent { 41 public static int t = parentStaticMethod2(); 42 43 static { 44 System.out.println("我是父类静态初始化块"); 45 } 46 { 47 System.out.println("我是父类非静态块"); 48 } 49 50 public Parent() { 51 System.out.println("我是父类构造函数"); 52 } 53 54 public static int parentStaticMethod() { 55 System.out.println("父类类的静态方法"); 56 return 10; 57 } 58 59 public static int parentStaticMethod2() { 60 System.out.println("父类的静态方法2"); 61 return 9; 62 } 63 64 @Override 65 protected void finalize() throws Throwable{ 66 super.finalize(); 67 System.out.println("销毁父类"); 68 } 69 70 } 71 72 class Child extends Parent { 73 74 public int i = childStaticMethod(); 75 76 { 77 System.out.println("子类非静态初始化块"); 78 } 79 static 80 { 81 System.out.println("子类静态初始化块"); 82 } 83 public Child() 84 { 85 System.out.println("子类的构造方法"); 86 } 87 public static int childStaticMethod() 88 { 89 System.out.println("子类的静态方法"); 90 return 1000; 91 } 92 @Override 93 protected void finalize() throws Throwable{ 94 // TODO Auto-generated method stub 95 super.finalize(); 96 System.out.println("销毁子类"); 97 } 98 99 }