We know that all final variables need initialization before they can be used.
So can we access a final variable before it is initialized?
Well, for the final instance variable and final class variable it is always
possible to access them before they are initialized.
We already know that all the instance variables and class variables have a
default value of 0, false or null, depending on their type.
Normally when we try to use any final variable before initialization, it would be compilation error.
e.g.
public class TestFinal {
private static final int STATIC_FINAL;
private final int INSTANCE_FINAL;
static {
System.out.println(STATIC_FINAL); // compilation error
STATIC_FINAL = 7;
}
TestFinal() {
System.out.println(INSTANCE_FINAL); // compilation error
INSTANCE_FINAL = 5;
}
public static void main(String[] args) {
new TestFinal();
}
}
The above code results in compilation errors for trying to access the two variables final variables
before they are initialized.
But if we add any accessor method for these final variables and use them before the initialization
it works and it prints the default value of 0 in this case.
e.g.
public class TestFinal {
private static final int STATIC_FINAL;
private final int INSTANCE_FINAL;
static {
// System.out.println(STATIC_FINAL);
System.out.println(getStaticFinal());
STATIC_FINAL = 7;
}
static int getStaticFinal() {
return STATIC_FINAL;
}
int getInstanceFinal() {
return INSTANCE_FINAL;
}
TestFinal() {
// System.out.println(INSTANCE_FINAL);
System.out.println(getInstanceFinal());
INSTANCE_FINAL = 5;
}
public static void main(String[] args) {
new TestFinal();
}
}
It would be good if the Java compiler could be updated to either detect the
usage of methods accessing the final variable before initialization and give error
or they should stop giving error for the access of the static and instance variables
which are final, if accessed before initialization, since they do have a default value
unlike the local variables.