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?
The reason why the code would not initially compile is because
defaultValueis an instance variable of the classTest, meaning that when an object of typeTestis created, a unique instance ofdefaultValueis also created and attached to that particular object. Because of this, it is not possible to referencedefaultValuein the constructor, as neither it, nor the object have been created yet.The solution is to make the final variable
static:By making the variable
static, it becomes associated with the class itself, rather than instances of that class and is shared amongst all instances ofTest. 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.References: