Why can't I create an enum in a Java inner class?

I am trying to do the following:

public class History { public class State { public enum StateType { 

Eclipse gives me this compilation error on StateType : The member enum StateType must be defined inside a static member type .

The error disappears when I set the State class. I could make a static State , but I don’t understand why I cannot declare enum in the inner class.

+46
java enums inner-classes nested
Feb 13 '13 at 16:20
source share
3 answers

enum types that are defined as nested types are always implicitly static (see JLS §8.9. Enumerations )

You cannot have a static nested type inside a non-static (it is also an "inner class", see JLS §8.1.3. Inner classes and Enclosing Instances ).

Therefore, you cannot have an internal enum type inside a non-static nested type.

+78
Feb 13 '13 at 16:23
source share

There is already enough information from + Joachim Sauer, I just add additional data.

You can define an inner enumeration only if your inner class is a static nested inner class. See below

 private static class DbResource { public enum DB { MERGE_FROM, MERGE_TO, MAIN; } } 
+1
Jan 30 '16 at 10:08
source share

If you declared enum as follows:

 enum Suit {SPADES, HEARTS, CLUBS, DIAMONDS} 

The Java compiler will synthesize the following class for you:

 final class Suit extends java.lang.Enum<Suit> { public static final Suit SPADES; public static final Suit HEARTS; public static final Suit CLUBS; public static final Suit DIAMONDS; private static final Suit[] $VALUES; public static Suit[] values(); public static Suit valueOf(java.lang.String); private Suit(); } 

There is no intention to create other instances of this class that are different from those static fields that are already defined in it (as you could infer from its private constructor), but most importantly, and as mentioned in the accepted answer, the inner class cannot have static members ( JLS §8.1.3. Inner classes and Enclosing instances ), and since the synthetic enum class does, this makes it unacceptable as an inner class.

+1
Oct 05 '17 at 21:29
source share



All Articles