Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        }
    };
}
like image 683
Morten Avatar asked Sep 25 '12 13:09

Morten


1 Answers

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

like image 84
Peter Lawrey Avatar answered Nov 03 '22 01:11

Peter Lawrey