Search code examples
javastatic-initializer

Static final field initialization from static initializer


Why isn't it possible to access static final fields from a corresponding static initializer using the declaring class as qualifier (in a static way)?

At first, I thought this was an Eclipse bug:

Eclipse bug?

I also consisted some lack of knowledge, because static initializers are not my everyday business. But lo and behold, this works without the class qualifier as expected:

Lack of knowledge?

To complete my test series, I gave it a try in the bash:

Damn!

causing the same result.

This leads me to the final question:

Is there any reason to prohibit the class qualifier when accessing static final fields from static initializer blocks? Because the declaring class wasn't initialized before?


Solution

  • In order to initialise a final variable in a initialization block, the simple name of the variable should be use. i.e. the variable name alone with out any qualifiers.

    It is stated on the java language specification as below

    "Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable, or its simple name qualified by this, occurs on the left hand side of an assignment operator. A Java compiler must carry out a specific conservative flow analysis to make sure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error must occur."