You cannot refer to a field before defining it, but only if you do not qualify it

I found that what was happening with the following code made my jaw drop out:

public class MCVE {

    { // instance initializer
        System.out.println(test); // cannot reference a field before it is defined
        System.out.println(this.test);
    }
    private final String test = "wat";
}

Line System.out.println(test);gives error

You cannot reference a field before defining it.

But the line is System.out.println(this.test); not

Why is it not a mistake when I qualify it?

+4
source share
2 answers

As with many of these issues, this is because JLS says so.

8.3.2.3 Restrictions on the use of fields during initialization

, ( static) C :

  • ( static) C ( static) C.
  • .
  • .
  • C - , .

, .

() " " - , . ( this) - , .

:

, , (.. ), ( this.test).

( )

+4

this , . test ( ). , test ( this).

-3

All Articles