I have gone through a number of posts on Stack overflow trying to find out why below Code 1 does not work , but Code 2 does. I found there was inconsistency in behavior or compilers in different version in ver 6 vs ver 7 as seen in post https://stackoverflow.com/questions/13864464/use-of-uninitialized-final-field-with-without-this-qualifier. This was more to do with accessing of default final variable with or without 'this'. However in jls 8 specs as per my understanding this point is very clear in first two lines here
Also I learned that accessing a final variable which is not yet definitely initialized directly (through simple name) is not allowed (Code 1). But the same works perfectly when accessed in a method (Code 2). I used jdk 1.8.0.141 to compile these code snippets and after running I get the output for Code 2 as shown.
I want to know how accessing the final variable via a method makes this difference. Is it because in this case the variable is accessed using this(implicitly due to method call). If so , why using 'this.x' in Code 1 instead of 'x' does not work.
Code 1:
class Test {
final int x;
{
System.out.println("Here is x " + x); // x replaced with this.x also does not work
x = 7;
printX();
}
Test() {
System.out.println("const called");
}
void printX() {
System.out.println("Here x is " + x);
}
public static void main(String[] args) {
Test t = new Test();
}
}
Does not compile : Variable x might not have been initialized. (Same for this.x)
Code 2:
class Test {
final int x;
{
printX();
x = 7;
printX();
}
Test() {
System.out.println("const called");
}
void printX() {
System.out.println("Here x is " + x);
}
public static void main(String[] args) {
Test t = new Test();
}
}
This complies and gives out (on different lines each)
Here x is 0 Here x is 7 const called
PS : The code has been taken originally from here