是否使这个私有枚举静态?
在类中,我需要定义传递到方法中的不同操作。现在,所有实例都可以安全地共享这些操作,因此我认为我可以安全地将枚举设为静态。
但在我见过的几乎所有示例中,嵌套枚举从来都不是静态的。那么,定义嵌套(私有)枚举的首选方法是什么?不使其静态实际上有意义吗?
public class MyClass {
private static enum Action {
READ("read"),
WRITE("write");
final String value;
Action(String value) {
this.value = value;
}
String getValue() {
return value;
}
}
// attributes, methods, constructors and so on
}
In a class, I need to define different actions which are passed into a method. Now, all instances can safely share these action, so I thought I could safely make the enum static.
But in almost all examples I've seen, the nested enum is never made static. So, which is the preferred way to define a nested (private) enum? Does it actually make sense to not make it static?
public class MyClass {
private static enum Action {
READ("read"),
WRITE("write");
final String value;
Action(String value) {
this.value = value;
}
String getValue() {
return value;
}
}
// attributes, methods, constructors and so on
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 语言规范第 8.9 节指出:
所以你可以,但你不必这样做,而且没有什么区别。就我个人而言,我认为我不会打扰,因为无论如何它都是隐含的。
The Java Language Specification, section 8.9, states:
So you can, but you don't have to, and it'll make no difference. Personally I don't think I'd bother, as it's implicit anyway.
嵌套枚举类型是隐式静态的:)
Nested enum types are implicitly static :)
由于 enum 本质上是静态的,因此在 enum 中使用 static 关键字没有必要,也没有什么区别。
As enum is inherently static, there is no need and makes no difference when using static-keyword in enum.