为什么静态初始化块中不允许有限定的静态最终变量? [英] Why isn't a qualified static final variable allowed in a static initialization block?
问题描述
class Program {
static final int var;
static {
Program.var = 8; // Compilation error
}
public static void main(String[] args) {
int i;
i = Program.var;
System.out.println(Program.var);
}
}
案例 2
class Program {
static final int var;
static {
var = 8; //OK
}
public static void main(String[] args) {
System.out.println(Program.var);
}
}
为什么案例 1 会导致编译错误?
Why does Case 1 cause a compilation error?
推荐答案
JLS 给出了答案(注意粗体声明):
The JLS holds the answer (note the bold statement):
同样,每个空白的 final 变量最多只能赋值一次;当分配给它时,它必须绝对未分配.这样的赋值被定义为当且仅当变量的简单名称(或者,对于字段,由 this 限定的简单名称)出现在赋值运算符的左侧时发生.[§16]
Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple name qualified by this) occurs on the left hand side of an assignment operator. [§16]
这意味着在分配静态最终变量时必须使用简单名称" - 即没有任何限定符的 var 名称.
This means that the 'simple name' must be used when assigning static final variables - i.e. the var name without any qualifiers.
这篇关于为什么静态初始化块中不允许有限定的静态最终变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!