0

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

Mayank Madhav
  • 429
  • 1
  • 7
  • 19
  • I am not sure why this question is not getting either an answer or any comment. If its too long I can shorten it and actually as far as question is concerned, It begins on in the last paragraph to be precise. Please let me know if its not clear or too verbose – Mayank Madhav Mar 09 '18 at 13:55

1 Answers1

-1

After sharing the question with some of my friends i got a link to this stack overflow post here

Though the accepted answer seems to be talking about a totally different concept of forward reference. It is the 2nd answer by @Tunaki, which is the correct answer as per my understanding. It also gives the right reference in jls 8 to section 16.2.2

Mayank Madhav
  • 429
  • 1
  • 7
  • 19