在Java中,类内的枚举类型是静态的吗?


123

我似乎无法像从内部类内部那样从枚举内部访问周围类的实例成员。这是否意味着枚举是静态的?是否可以访问周围类的实例的范围,还是我必须在需要的地方将实例传递给枚举的方法?

public class Universe {
    public final int theAnswer;

    public enum Planet {
        // ...
        EARTH(...);
        // ...

        // ... constructor etc.

        public int deepThought() {
            // -> "No enclosing instance of type 'Universe' is accessible in this scope"
            return Universe.this.theAnswer;
        }
    }

    public Universe(int locallyUniversalAnswer) {
        this.theAnswer = locallyUniversalAnswer;
    }
}

我不确定我是否完全理解您要描述的内容。可以给一个小的代码示例吗?
皮特2009年

Answers:



45

创建实例级(非静态)内部枚举类是没有意义的-如果枚举实例本身与外部类绑定,则它们会破坏枚举保证-

例如,如果你有

public class Foo {
   private enum Bar {
        A, B, C;
   } 
}

为了使枚举值正确地充当常量,(伪代码,忽略访问限制)

Bar b1 = new Foo().A
Bar b2 = new Foo().A

b1和b2必须是相同的对象。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.