无法引用“X”在超类型构造函数被调用之前,其中x是最终变量 [英] Cannot reference "X" before supertype constructor has been called, where x is a final variable
问题描述
考虑下面的Java类声明:
Consider the following Java class declaration:
public class Test {
private final int defaultValue = 10;
private int var;
public Test() {
this(defaultValue); // <-- Compiler error: cannot reference defaultValue before supertype constructor has been called.
}
public Test(int i) {
var = i;
}
}
代码将无法编译,我上面突出显示的行。为什么会发生这个错误,最好的解决方法是什么?
The code will not compile, with the compiler complaining about the line I've highlighted above. Why is this error happening and what's the best workaround?
推荐答案
$ c> defaultValue 是类 Test
的实例变量,意味着当类型 Test
,创建 defaultValue
的唯一实例并附加到该特定对象。因为这一点,不可能在构造函数中引用 defaultValue
,因为它和对象都还没有创建。
The reason why the code would not initially compile is because defaultValue
is an instance variable of the class Test
, meaning that when an object of type Test
is created, a unique instance of defaultValue
is also created and attached to that particular object. Because of this, it is not possible to reference defaultValue
in the constructor, as neither it, nor the object have been created yet.
解决方案是使最终变量 static
:
The solution is to make the final variable static
:
public class Test {
private static final int defaultValue = 10;
private int var;
public Test() {
this(defaultValue);
}
public Test(int i) {
var = i;
}
}
通过使变量 static
,它与类本身关联,而不是该类的实例,并且在 Test
的所有实例之间共享。当JVM首次加载类时,将创建静态变量。因为类在你使用它创建一个实例时已经被加载了,所以静态变量已经可以使用,所以可以在类中使用,包括构造函数。
By making the variable static
, it becomes associated with the class itself, rather than instances of that class and is shared amongst all instances of Test
. Static variables are created when the JVM first loads the class. Since the class is already loaded when you use it to create an instance, the static variable is ready to use and so can be used in the class, including the constructor.
参考文献:
- Forum post asking the same question
- Understanding Instance and Class Members
- Explanation of how classloader loads static variables
这篇关于无法引用“X”在超类型构造函数被调用之前,其中x是最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!