为什么我不能在 Java 的内部类中创建枚举? [英] Why can't I create an enum in an inner class in Java?
问题描述
我尝试做的是:
public class History {
public class State {
public enum StateType {
Eclipse 在 StateType
上给了我这个编译错误:必须在静态成员类型中定义成员枚举 StateType
.
Eclipse gives me this compile error on StateType
: The member enum StateType must be defined inside a static member type
.
当我将 State
类设为静态时,错误就会消失.我可以将 State
设为静态,但我不明白为什么我不能在内部类中声明 enum
.
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.
推荐答案
enum
定义为嵌套类型的类型总是隐式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).
因此,在非静态嵌套类型中不能有 enum
内部类型.
Therefore you can't have an enum
inner type inside a non-static nested type.
这篇关于为什么我不能在 Java 的内部类中创建枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!