In Java, are enum types inside a class static?

Hanno Fietz picture Hanno Fietz · Mar 19, 2009 · Viewed 68.9k times · Source

I can't seem to access instance members of the surrounding class from inside an enum, as I could from inside an inner class. Does that mean enums are static? Is there any access to the scope of the surrounding class's instance, or do I have to pass the instance into the enum's method where I need it?

public class Universe {
    public final int theAnswer;

    public enum Planet {
        // ...
        EARTH(...);
        // ...

        // ... constructor etc.

        public int deepThought() {
            // -> "No enclosing instance of type 'Universe' is accessible in this scope"
            return Universe.this.theAnswer;
        }
    }

    public Universe(int locallyUniversalAnswer) {
        this.theAnswer = locallyUniversalAnswer;
    }
}

Answer

Jon Skeet picture Jon Skeet · Mar 19, 2009

Yes, nested enums are implicitly static.

From the language specification section 8.9:

Nested enum types are implicitly static. It is permissable to explicitly declare a nested enum type to be static.