By
Moment Only
更新日期:
Java的类初始化顺序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| package com.szxy;
public class InitClassTest { public static void main(String[] args) { new B(); } } class A{ static A a = new A(); static{ System.out.println("A:static"); } C c = new C(); { System.out.println("A:not static"); } public A() { System.out.println("A:constructor"); } } class B extends A { static{ System.out.println("B:static"); } static B b = new B(); { System.out.println("B:not static"); } public B() { System.out.println("B:constructor"); } } class C{ public C() { System.out.println("C"); } }
|
console打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| C //1) A:not static //1) A:constructor //1) A:static //2) B:static //3) C //4) A:not static //4) A:constructor //4) B:not static //4) B:constructor //4) C //5) A:not static //6) A:constructor //7) B:not static //8) B:constructor //9)
|
根据打印结果:父类静态变量(静态代码块)-> 子类静态变量(静态代码块)
-> 父类成员变量(非静态代码块)-> 父类构造方法 ->子类成员变量(非静态代码块)
-> 子类构造方法
ps:静态变量和静态代码块属于平级,谁在前谁先初始化;
非静态代码块和成员变量属于平级,谁在前谁先初始化