Java 初始化顺序 发表于 2016-12-30 | 分类于 Java SE 初始化操作的执行顺序: 所有静态成员/初始块先执行 父类初始化完成(非静态成员/初始块执行 -> 构造函数调用) 子类初始化完成(非静态成员/初始块执行 -> 构造函数调用) 例子:1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677/** * 父类 */public class Parent { static int a1 = intA1(); static int intA1(){ System.out.println("1. Parent, static int a1 = intA1();"); return 0; } { System.out.println("6. Parent, non-static initial block1"); } static { System.out.println("2. Parent, static initial block1"); } { System.out.println("7. Parent, non-static initial block2"); } static { System.out.println("3. Parent, static initial block2"); } static int a2 = intA2(); static int intA2(){ System.out.println("4. Parent, static int a2 = intA2();"); return 0; } public Parent() { System.out.println("8. Parent, constructor method"); }}/** * 子类 */public class Child extends Parent{ { System.out.println("9. Child, non-static initial block1"); } int c1 = intC1(); int intC1(){ System.out.println("10. Child, int c1 = intC1();"); return 0; } { System.out.println("11. Child, non-static initial block2"); } static{ System.out.println("5. Child, static initial block1"); } public Child() { System.out.println("12. Child, constructor method"); }}/** * 测试类 */public class ExeSeqTest { public static void main(String[] args) { Child child = new Child(); }} 执行顺序结果如下:1234567891011121. Parent, static int a1 = intA1();2. Parent, static initial block13. Parent, nonstatic initial block24. Parent, static int a2 = intA2();5. Child, static initial block16. Parent, non-static initial block17. Parent, non-static initial block28. Parent, constructor method9. Child, non-static initial block110. Child, int c1 = intC1();11. Child, non-static initial block212. Child, constructor method