在Java中,类中的枚举类型是静态的吗?
我似乎无法从枚举内部访问周围类的实例成员,就像我可以从内部类内部访问一样。 这是否意味着枚举是静态的? 是否可以访问周围类实例的范围,或者我是否必须将实例传递到我需要的枚举方法中?
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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,嵌套枚举是隐式静态的。
来自语言规范第 8.9 节:
Yes, nested enums are implicitly static.
From the language specification section 8.9:
制作实例级(非静态)内部枚举类是没有意义的 - 如果枚举实例本身与外部类绑定,它们就会破坏枚举保证 -
例如,如果您有
正确的枚举值作为常量,(伪代码,忽略访问限制)
b1 和 b2 必须是相同的对象。
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
For the enum values to properly act as constants, (psuedocode, ignoring access restrictions)
b1 and b2 would have to be the same objects.