Search code examples
javaenumsnestedinner-classes

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.


Solution

  • This is allowed in Java 16+

    This is no longer forbidden starting with Java 16 (and the later LTS release Java 17) thanks to JEP 395 relaxing the rules on some static types inside inner classes.

    The new phrasing in §8.1.3. Inner Classes and Enclosing Instances is (emphsis mine):

    All of the rules that apply to nested classes apply to inner classes. In particular, an inner class may declare and inherit static members (§8.2), and declare static initializers (§8.7), even though the inner class itself is not static.

    This answer explains the change in more detail.

    Before Java 16 it was forbidden:

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

    A nested enum type is implicitly static.

    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):

    It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable

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