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

1. 父类静态块/域(静态块和静态域谁在前谁先初始化)

2. 子类静态块/域(静态块和静态域谁在前谁先初始化)

3. 父类构造块

4. 父类构造函数

5. 子类构造块

6. 子类构造函数

😊 一道有意思的静态块、构造块的题目

package com.ryan.project.translaterecorder.demo;

public class B {

    private static B b1 = new B();
    private static B b2 = new B();

    {
        System.out.println("构造块");
    }

    static {
        System.out.println("静态块");
    }

    public B(){
        System.out.println("默认构造器");
    }
    public static void main(String[] args){
        B b = new B();
    }
}

代码实现:

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