Nested enum is static?

Your declaration of method() is in the wrong place. You declare it in the constant body. But it doesn't override anything. It belongs in the enum body, not the instance body.

The instance subtype is declared in the static initializer for the enum constant. Since the context is static it does not have access to the enum instance variables.

Your enum declaration is not static, it is top-level, and top-level classes cannot be static.

Constant bodies define an implicit nested anonymous subclass of the enum, and do not constitute nested enums as meant by the JLS. Each constant is of a different anonymous subtype of the enum you're declaring, which subtype is not static. However, the subtype is declared in a static context, so that's why the code can't reach the instance variable.

EDIT: Useful references from the JLS

https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.1 "The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors. Instance methods declared in these class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type (§8.4.8)."

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9.5 "An anonymous class declaration is automatically derived from a class instance creation expression by the Java compiler. An anonymous class is never abstract (§8.1.1.1). An anonymous class is always implicitly final (§8.1.1.2). An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1)."

Tags:

Java

Enums