在继承关系中的类中静态域,静态块,构造块,构造函数,main()函数初始化顺序:

  1. 父类静态块/域(静态块和静态域谁在前谁先初始化)
  2. 子类静态块/域(静态块和静态域谁在前谁先初始化)
  3. 父类构造块
  4. 父类构造函数
  5. 子类构造块
  6. 子类构造函数

代码实现:

父类:

package com.ryan.parent.requestweb;

public class Father {

    private static String staticProperty = "static property in father";

    static {
        System.out.println(staticProperty);
        System.out.println("in father static block");
    }

    {
        System.out.println("in father construct block");
    }

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

    public static void main(String[] args) {
        new Son();
    }
}

子类:

package com.ryan.parent.requestweb;

public class Son extends Father {

    private static String staticProperty = "staticProperty in son";

    static {
        System.out.println(staticProperty);
        System.out.println("in son static block");
    }

    {
        System.out.println("in son construct block");
    }

    public Son() {
        System.out.println("in son constructor");
    }
}

运行结果:

static property in father
in father static block
staticProperty in son
in son static block
in father construct block
in father constructor
in son construct block
in son constructor