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? :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With