Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What I try to do is this:

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

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

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

like image 417
Steven Roose Avatar asked Feb 13 '13 16:02

Steven Roose


People also ask

Can we create enum inside class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

How do you add an enum to a class in Java?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Why inner classes Cannot have static declarations?

Quoting another answer, It's because an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself.

Can we define enum inside interface?

Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version.


2 Answers

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

You can't have a static nested type inside a non-static one (a.k.a an "inner class", see JLS §8.1.3. Inner Classes and Enclosing Instances).

Therefore you can't have an enum inner type inside a non-static nested type.

like image 80
Joachim Sauer Avatar answered Sep 19 '22 16:09

Joachim Sauer


If you declared an enum like this:

enum Suit {SPADES, HEARTS, CLUBS, DIAMONDS} 

The Java compiler would synthetically generate 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 other than those static fields already defined in it (as you could infer from its private constructor), but most importantly, and as mentioned in the accepted answer, a inner class cannot have static members (JLS §8.1.3. Inner Classes and Enclosing Instances), and since the enum synthetic class does, it makes it unacceptable as inner class.

like image 45
Edwin Dalorzo Avatar answered Sep 20 '22 16:09

Edwin Dalorzo