In Java, are enum types inside a class static?
我似乎无法从枚举内部访问周围类的实例成员,因为我可以从内部类内部访问。这是否意味着枚举是静态的?是否可以访问周围类实例的作用域,或者是否必须将该实例传递到需要它的枚举方法中?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } } |
是的,嵌套枚举是隐式静态的。
从语言规范第8.9节:
Nested enum types are implicitly
static. It is permissable to
explicitly declare a nested enum type
to be static.
号
使实例级别(非静态)的内部枚举类没有意义-如果枚举实例本身绑定到外部类,则会破坏枚举保证-
例如,如果你有
1 2 3 4 5 | public class Foo { private enum Bar { A, B, C; } } |
使枚举值正确地充当常量(psuedCode,忽略访问限制)
1 2 | Bar b1 = new Foo().A Bar b2 = new Foo().A |
号
b1和b2必须是相同的物体。