Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
Franz Ebner Avatar asked Aug 13 '14 11:08

Franz Ebner


2 Answers

Actually, you can initialize a static field from a static initializer.

But I think (I'm not sure), you are having another problem. The problem here is that you're (according to the compiler) trying to assign a final field. However, your true intention is not to assign it.. you're trying to initialize it. But the compiler doesn't get this.

When you call something like Test.I the compiler will think you are trying to modify a static variable that it may be previously initialized (i.e. from a static initializer). The compiler is not that smart to see that you're actually initializing your variable, it's just interpreting you're assigning a static variable from a class, be it Test or be it Foo.

However, if you call it without the class qualifier, the compiler knows that you're trying to modify your own static variable, and in a static initializer, so the operation is safe for the final field.

Please, I hope I'm being clear enough, and please, be noted that I'm not sure about this behaviour.

like image 134
Matias Cicero Avatar answered Oct 13 '22 01:10

Matias Cicero


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."

like image 24
Ranuka Avatar answered Oct 13 '22 01:10

Ranuka