Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java compile error depends on whether static variable name is qualified?

Tags:

java

javac

Why does this java program not compile:

public class xx {
    public static final Object obj;
    static {
//        obj = null;       // this compiles
        xx.obj = null;      // this doesn't
    }
}

with this error:

$ javac xx.java
xx.java:5: cannot assign a value to final variable obj
        xx.obj = null;      // this doesn't
          ^
1 error
$ javac -version
javac 1.6.0_33

when, if I replace xx.obj = null with obj = null (as alluded to in the comment) it does compile.

I thought the xx. class name prefix was more-or-less just syntax... is this a bug in the compiler or the language spec? :)

like image 477
Archie Avatar asked Jul 29 '12 00:07

Archie


1 Answers

When you do xx.obj, it means the class is already initialized. So final obj cannot be initialized again. This is a compile time error. Compiler could have checked that obj has not been initialized yet. It would be difficult to check that, but in theory it is possible. But that is not how Java compiler works.

like image 185
fastcodejava Avatar answered Sep 20 '22 06:09

fastcodejava