问题描述
例如,考虑下面的代码捕捉:
For example, consider code snap below:
public static final int a;
public static final int b;
static {
a = 8; // it's working
Test.b = 10; // compilation error Test.b cannot be assigned.
}
为什么我们不能使用 Test.b = 10;
在 Test
类本身的静态块内?没有班级名称它工作正常。
Why can't we use Test.b = 10;
inside a static block of the Test
class itself? Without the class name it's working fine.
这背后有什么理由吗?
推荐答案
必须在使用前初始化静态最终变量。它可以在声明时直接初始化,也可以在静态块中初始化。
A static final variable must be initialized before use. It may be initialized either directly at declaration time, or in a static block.
但是当你使用 class.var = x 它不被视为初始化而是作为赋值。
But when you use
class.var = x
it is not seen as an initialization but as an assignation.
对于JDK 7,错误是无法为最终变量赋值。
With a JDK 7, the error is cannot assign a value to final variable.
这解释了为什么它会删除
final
关键字
That explains why it works if you remove the
final
keyword
class Test {
static final int a = 2; // initialization at declaration time
static final int b;
static final int c;
static {
b = 4; // initialization in static block
Test.c = 6; // error : cannot assign a value to final variable c
}
...
}
编辑
在JLS中,正确的初始化词是明确的分配
In the JLS the correct word for initialization is definite assignement
从JLS中提取:
对于本地变量的每次访问或空白的最终字段x,x必须是肯定是在访问之前分配
,或者发生编译时错误。
同样,每个空白的最终变量必须在最多一次;当它的赋值发生时,它必须是
绝对未分配。
这样的赋值定义为当且仅当
变量的简单名称(或者,对于字段,由此限定的简单名称)出现在赋值运算符的左侧
侧。
Such an assignment is defined to occur if and only if either the simple name of thevariable (or, for a field, its simple name qualified by this) occurs on the left handside of an assignment operator.
对于空白最终变量的每个赋值,变量必须在赋值之前绝对是
未分配,否则会发生编译时错误。 / em>
For every assignment to a blank final variable, the variable must be definitelyunassigned before the assignment, or a compile-time error occurs.
强调我的,但我认为这是错误的真正原因。
emphasize mine, but I think this is the real reason for the error.
这篇关于为什么我们不能通过类名在静态块中设置静态最终变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!