嵌套的 Java 枚举定义 - 声明为静态有区别吗? [英] Nested Java enum definition - does declaring as static make a difference?

查看:45
本文介绍了嵌套的 Java 枚举定义 - 声明为静态有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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...
}

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

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

public interface Particle {

    static enum Charge {
        POSITIVE, NEGATIVE
    }

    Charge getCharge();

    double getMass();

    etc...
}

推荐答案

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

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

嵌套的枚举类型是隐式的静止的.允许显式声明嵌套的枚举类型保持静态.

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};
}

另一个带有嵌套 private 枚举(非隐式公开)的示例.

Another example with a nested private enum (not implicitly public).

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

这篇关于嵌套的 Java 枚举定义 - 声明为静态有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆