java 使这个私有枚举静态与否?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7418214/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:53:05  来源:igfitidea点击:

Make this private enum static or not?

javaenums

提问by helpermethod

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
}

回答by Jon Skeet

The Java Language Specification, section 8.9, states:

Java语言规范,8.9节,规定:

Nested enum types are implicitly static. It is permissable to explicitly declare a nested enum type to be static.

嵌套的枚举类型是隐式静态的。允许将嵌套枚举类型显式声明为静态。

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.

所以你可以,但你没有必要,这不会有什么区别。就我个人而言,我认为我不会打扰,因为无论如何它都是隐含的。

回答by Miserable Variable

Nested enum types are implicitly static :)

嵌套的枚举类型是隐式静态的 :)

回答by Kal

If an enum is a member of a class, it is implicitly static

如果枚举是类的成员,则它是隐式静态的

回答by Danail Tsvetanov

As enum is inherently static, there is no need and makes no difference when using static-keyword in enum.

由于 enum 本质上是静态的,因此在 enum 中使用 static-keyword 时没有必要并且没有任何区别。