In Java, are enum types inside a class static?

JavaEnumsScope

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

It wouldn't make sense to make an instance-level (non-static) inner enum class - if the enum instances were themselves tied to the outer class they'd break the enum guarantee -

e.g. if you had

public class Foo {
   private enum Bar {
        A, B, C;
   } 
}

For the enum values to properly act as constants, (psuedocode, ignoring access restrictions)

Bar b1 = new Foo().A
Bar b2 = new Foo().A

b1 and b2 would have to be the same objects.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHanno FietzView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaSteve B.View Answer on Stackoverflow