是否使这个私有枚举静态?

发布于 2024-12-04 16:46:57 字数 494 浏览 2 评论 0原文

在类中,我需要定义传递到方法中的不同操作。现在,所有实例都可以安全地共享这些操作,因此我认为我可以安全地将枚举设为静态。

但在我见过的几乎所有示例中,嵌套枚举从来都不是静态的。那么,定义嵌套(私有)枚举的首选方法是什么?不使其静态实际上有意义吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

停顿的约定 2024-12-11 16:46:57

Java 语言规范第 8.9 节指出:

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

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

The Java Language Specification, section 8.9, states:

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.

↘紸啶 2024-12-11 16:46:57

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

Nested enum types are implicitly static :)

拥有 2024-12-11 16:46:57

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

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

天荒地未老 2024-12-11 16:46:57

由于 enum 本质上是静态的,因此在 enum 中使用 static 关键字没有必要,也没有什么区别。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文