嵌套的 Java 枚举定义 - 声明为静态有区别吗?

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

Nested Java enum definition - does declaring as static make a difference?

javaenumsclass-design

提问by serg10

I have an interface - here's a nicely contrived version as an example:

我有一个界面——这里有一个精心设计的版本作为例子:

public interface Particle {

    enum Charge {
        POSITIVE, NEGATIVE
    }

    Charge getCharge();

    double getMass();

    etc...
}

Is there any difference in how implementations of this would behave if I defined the Chargeenum as static - i.e. does this have any effect:

如果我将Charge枚举定义为静态,它的实现方式是否有任何不同- 即这是否有任何影响:

public interface Particle {

    static enum Charge {
        POSITIVE, NEGATIVE
    }

    Charge getCharge();

    double getMass();

    etc...
}

采纳答案by idrosid

No, it makes no difference. However the reason is not because it is a member declaration inside an interface, as Jon says. The real reason is according to language spec (8.9) that

不,这没有区别。然而,正如 Jon 所说,原因并不是因为它是接口内的成员声明。真正的原因是根据语言规范(8.9

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

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

At the following example static does not make any difference either (even though we have no interface):

在以下示例中,静态也没有任何区别(即使我们没有接口):

public class A {
  enum E {A,B};
}

public class A {
  static enum E {A,B};
}

Another example with a nested privateenum (not implicitly public).

另一个带有嵌套私有枚举的示例(不是隐式公开的)。

public class A {
  private static enum E {A,B}
}

回答by Jon Skeet

No, it makes no difference. From the language spec, section 9.5:

不,这没有区别。从语言规范,第 9.5 节

Interfaces may contain member type declarations (§8.5). A member type declaration in an interface is implicitly staticand public.

接口可能包含成员类型声明(第8.5 节)。接口中的成员类型声明是隐式staticpublic