Java变量初始化顺序

结论

三条规则:

  1. 类级别:静态变量,静态初始化块
  2. 对象级别:成员变量,初始化块,构造方法
  3. 父类和子类:先父类后子类

例子:

父类代码:

public class Father {
    private PrintStream field = System.out.printf("father field\n");
    private static PrintStream staticField = System.out.printf("father static field\n");
    private String name;
    private int age;
    private String address;

    static {
        System.out.println("father static domain");
    }

    {
        System.out.println("father field domain");
    }

    public Father() {
        System.out.println("father constructor");
    }


子类代码:

public class Child extends Father {
    private PrintStream field = System.out.printf("child field\n");
    private static PrintStream staticField = System.out.printf("child static field\n");
    private String name;
    private int age;
    private String address;

    static {
        System.out.println("child static domain");
    }

    {
        System.out.println("child field domain");
    }

    public Child() {
        System.out.println("child constructor");
    }

测试代码:

public class Test {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

输出结果:
father static field
father static domain
child static field
child static domain
father field
father field domain
father constructor
child field
child field domain
child constructor