我正在研究 Java 中的静态初始化器。我通过下面给出的源代码来了:
public class A {
private static int count = 5;
final static int STEP = 10;
boolean alive;
static {
count = 1;
}
public static void main(String[] args) {
A a = new A();
System.out.println(A.count);
}
}
我的问题是,为什么编译器不提示变量 count
在 count = 1
中被重新赋值为 1
初始化 block 。我知道 Java 允许前向引用,只要遵循 declaration-before-read 规则(即在声明之前不应读取任何标识符),这适用于所有初始化程序,如果不是,则引用(或标识符) ) 必须位于赋值的左侧。我也知道,如果多个静态初始化表达式和静态字段初始化 block 写在一个类中,那么它们的执行顺序是顺序的。
根据我的说法,执行流程应该是:加载类,然后按顺序执行所有静态初始化程序(表达式和 block ),因此 count
将被初始化为值5
然后默认构造函数将被调用 super() 并将实例变量 alive
初始化为默认值。但是为什么它没有抛出静态变量 count
已被重新初始化的错误(因为它不是前向引用的情况),而是给出输出 1
.
这是否意味着我们可以通过静态初始化 block 重新初始化静态变量?
最佳答案
因为您的类变量在使用前出现,所以没问题。
这是 language specification#Static Initializers
同样的
A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.
Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.3 for the precise rules governing forward reference to class variables.
关于java - 为什么静态初始化程序允许在 Java 中重新初始化静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44904324/