执行从抽象 class 派生的子 class' 静态块

Execution of child class' static block derived from abstract class

public class Test15 {
    public static void main(String[] args) {
        System.out.println(B.x);
    }
}

abstract class A { 
    static int x=99;

    A() {
        System.out.println("A DC");
    }

    static {
        System.out.println("A SB");
    }
}

class B extends A {
    static {
        System.out.println("B Sb");
    }
}

为什么在上面的程序中子 class 静态块没有被执行?

x 是 class Astatic 变量,所以即使你通过 B.x 访问它,也不需要初始化 class B。因此,class Bstatic 初始化程序不会被执行。

这是相关的JLS 12.4.1 quote

A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

B的静态块只会在classB初始化时执行。调用其超classA的域x不会导致classB被初始化。

来自 Java 规格:

12.4.1 When Initialization Occurs

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

• T is a class and an instance of T is created.

• T is a class and a static method declared by T is invoked.

• A static field declared by T is assigned.

• A static field declared by T is used and the field is not a constant variable (§4.12.4).

• T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.