While coding, I have encountered a strange Java Compiler behaviour.
When compiling the class (source below), the compiler emits an error ("inner classes cannot have static declarations
") on the NULL class variable. This is as expected!
However, no error is generated on the ZERO class variable. This I don't understand!
Why this difference, which seems to allow static declarations of simple types, but not Objects, in inner classes.
(javac -version: 1.6.0_24)
public class Outer {
public static final Runnable HELLO = new Runnable() {
// No compiler error
public static final int ZERO = 0;
// Causes compiler error: "inner classes cannot have static declarations"
public static final Object NULL = null;
@Override
public void run() {
System.out.println("Hello " + ZERO + NULL);
}
};
}
The problem is that inner classes cannot have a static initialiser block which is required to initialise non-trivial constants and non-constants.
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