以下 Java 代码不调用类 B
的静态初始值设定项。为什么?
代码:
class A
{
static
{
System.out.println("A static init");
}
public static void f()
{
System.out.println("f() called");
}
}
class B extends A
{
static
{
System.out.println("B static init");
}
}
public class App
{
public static void main( String[] args)
{
B.f(); //invokestatic #16 // Method com/db/test/B.f:()V
}
}
程序输出:
A static init
f() called
在 JDK 1.8.0_25 上测试
最佳答案
没有“静态构造函数”这样的东西。它是一个静态初始化 block ,仅在类初始化时执行。由于您调用的是 A 类的静态方法(即使您是通过 B 类引用它),因此无需初始化 B 类。调用 B.f();
与调用 相同code>A.f();
.
如果您创建 B 类的实例或访问 B 类的静态成员/方法,将执行 B 类的静态初始化 block 。
以下是触发类初始化的唯一条件(JLS 12.4.1):
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.
关于java - 未为派生类调用静态初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923010/