Java类的成员初始化顺序
2017-06-01
代码:
public class InitializeSequence { public static void main(String[] args) { new Son(); } } class Father { static { System.out.println("1 父类静态代码块初始化"); } { System.out.println("5 父类代码块初始化"); } private static String s = print("2 父类静态实例"); private String s1=print("6 父类实例"); public static String print(String msg) { System.out.println(msg); return "父类静态成员变量的初始化"; } public Father() { System.out.println("7 父类无参构造函数初始化"); } } class Son extends Father { static { System.out.println("3 子类静态代码块初始化"); } { System.out.println("8 子类代码块初始化"); } private static String s = print("4 子类静态实例"); private String s1=print("9 子类实例"); public static String print(String msg) { System.out.println(msg); return "子类静态成员变量的初始化"; } public Son() { System.out.println("10子类构造函数初始化"); } }
结果:
1 父类静态代码块初始化
2 父类静态实例
3 子类静态代码块初始化
4 子类静态实例
5 父类代码块初始化
6 父类实例
7 父类无参构造函数初始化
8 子类代码块初始化
9 子类实例
10子类构造函数初始化
总结:
1 先静态成员,后实例成员
2 先父类,后子类
3 先实例成员,后构造函数
对比:c#类的成员初始化顺序