继承中的静态块 vs 初始​​化块 vs 构造函数

我找到了这个例子,我想了解它背后的逻辑?构造函数和静态块以及初始化块如何在继承中工作?分别在哪个阶段被调用?

i find this example and i want to understand the logic behind it ? how constructors and static blocks and initializer blocks works in inheritance ? in which stage each one is called ?

public class Parent {

    static {
        System.out.println("i am Parent 3");
    }

    {
        System.out.println("i am parent 2");
    }

    public Parent() {
        System.out.println("i am parent 1");
    }

}

public class Son extends Parent {

    static {System.out.println("i am son 3");}
    {System.out.println("i am son 2");}

    public Son() {
        System.out.println("i am son 1");
    }

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

输出是:

i am Parent 3
i am son 3
i am parent 2
i am parent 1
i am son 2
i am son 1

推荐答案

当类被JVM加载和初始化时,静态块被调用一次.实例初始化器在构造类的实例时执行,就像构造函数一样.

A static block is called once, when the class is loaded and initialized by the JVM. An instance initializer is executed when an instance of the class is constructed, just like a constructor.

Java 语言规范中描述了静态和实例初始化程序

相关文章