gpt4 book ai didi

java - 执行从抽象类派生的子类的静态 block

转载 作者:行者123 更新时间:2023-11-30 06:42:13 25 4
gpt4 key购买 nike

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");
}
}

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

最佳答案

xA 类的 static 变量,因此即使您通过 B.x 访问它,也有无需初始化类 B。因此,类 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.

关于java - 执行从抽象类派生的子类的静态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com