为什么我不能在Java的内部类中创建一个枚举?

为什么我不能在Java的内部类中创建一个枚举?

问题描述:

我尝试做的是这样的:

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

Eclipse在 StateType 成员枚举状态类型必须在静态成员类型中定义。

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

错误消失当我使状态类静态时。我可以使 State static,但我不明白为什么我不能在内部类中声明一个枚举 / p>

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.

枚举定义为嵌套类型的类型总是隐式 static (请参阅 JLS§8.9。枚举

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

您不能在非静态嵌套类型(也称为内部类,请参阅 JLS§8.1 .3。内部类和封闭实例)。

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.