javacompiler-errors

Java Compiler error puzzler: "inner classes cannot have static declarations" - except for simple types


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);
        }
    };
}

Solution

  • The problem is that inner classes cannot have a static initialiser block which is required to initialise non-trivial constants and non-constants.