在 Java 中,类中的枚举类型是静态的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/663834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java, are enum types inside a class static?
提问by Hanno Fietz
I can't seem to access instance members of the surrounding class from inside an enum, as I could from inside an inner class. Does that mean enums are static? Is there any access to the scope of the surrounding class's instance, or do I have to pass the instance into the enum's method where I need it?
我似乎无法从枚举内部访问周围类的实例成员,就像我可以从内部类内部一样。这是否意味着枚举是静态的?是否可以访问周围类的实例的范围,或者我是否必须将实例传递到我需要的枚举方法中?
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;
}
}
采纳答案by Jon Skeet
Yes, nested enums are implicitly static.
是的,嵌套枚举是隐式静态的。
From the language specification section 8.9:
来自语言规范第 8.9 节:
Nested enum types are implicitly static. It is permissable to explicitly declare a nested enum type to be static.
嵌套的枚举类型是隐式静态的。允许将嵌套枚举类型显式声明为静态。
回答by Steve B.
It wouldn't make sense to make an instance-level (non-static) inner enum class - if the enum instances were themselves tied to the outer class they'd break the enum guarantee -
制作实例级(非静态)内部枚举类是没有意义的——如果枚举实例本身与外部类相关联,它们就会破坏枚举保证——
e.g. if you had
例如,如果你有
public class Foo {
private enum Bar {
A, B, C;
}
}
For the enum values to properly act as constants, (psuedocode, ignoring access restrictions)
为了使枚举值正确地充当常量,(伪代码,忽略访问限制)
Bar b1 = new Foo().A
Bar b2 = new Foo().A
b1 and b2 would have to be the same objects.
b1 和 b2 必须是相同的对象。