枚举的实例默认是静态的吗?
enum Animals{
DOG("woof"),
CAT("Meow"),
FISH("Burble");
String sound;
Animals(String s) {
sound = s;
}
}
public class TestEnum{
static Animals a;
public static void main(String ab[]){
System.out.println( a );
System.out.println( a.DOG.sound + " " + a.FISH.sound);
}
}
在上面的示例中,为什么当 a
为 null 并且枚举未声明为静态时,我们能够访问枚举的实例(即作为 a.DOG.sound)? 枚举实例默认是静态的吗?
enum Animals{
DOG("woof"),
CAT("Meow"),
FISH("Burble");
String sound;
Animals(String s) {
sound = s;
}
}
public class TestEnum{
static Animals a;
public static void main(String ab[]){
System.out.println( a );
System.out.println( a.DOG.sound + " " + a.FISH.sound);
}
}
In the above example, why are we able to access instances of the enum (i.e. as a.DOG.sound) when a
is null and enum is not declared as static?
Are the enum instances static by default?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
枚举是隐式的
public static final
。您可以引用
a.DOG
,因为您可以通过实例引用访问静态成员,即使为null:静态解析使用引用类型,而不是实例。我不会;这是误导性的:约定有利于类型(而不是实例)静态引用。
有关类的信息,请参阅 JLS 6.5.6.2通过实例变量。请参阅 JLS 15.11 了解为什么它仍然适用于一个
空
。简而言之:它是引用类型,而不是实例,通过它解析静态。更新的链接:/
JSE 6
JSE 7
JSE 8
Enums are implicitly
public static final
.You can refer to
a.DOG
because you may access static members through instance references, even when null: static resolution uses the reference type, not the instance.I wouldn't; it's misleading: convention favors type (not instance) static references.
See JLS 6.5.6.2 regarding class variable via instances. See JLS 15.11 for why it still works with a
null
. Nutshell: it's the reference type, not the instance, through which statics are resolved.Updated links :/
JSE 6
JSE 7
JSE 8
是的,枚举实际上是静态的。
Yes, enums are effectively static.