枚举的实例默认情况下是静态的吗? [英] Are instances of enums static by default?
问题描述
DOG(woof),
CAT(喵),
FISH(Burble);
字符串声;
动物(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并且枚举未声明为静态时,枚举的实例(即as.DOG.sound)
默认情况下枚举实例是否静态?
枚举是隐式的 public static final
。
您可以参考 a.DOG
,因为您可以通过实例引用访问静态成员,即使是null:静态分辨率使用引用类型,而不是实例。
我不会;这是误导的:惯例喜欢类型(不是实例)静态引用。
请参阅 JLS 6.5.6.2 。请参阅 JLS 15.11 ,为什么它仍然适用一个 null
。 Nutshell:它是参考类型,而不是通过这些静态解析的实例。
更新的链接:/
JSE 6
JSE 7
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?
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
- JLS 6.5.6.2 regarding class variable access via expression name
- JLS 15.11 regarding static field access via null references
JSE 7
- JLS 6.5.6.2 regarding class variable access via expression name
- JLS 15.11 regarding static field access via null references
JSE 8
- JLS 6.5.6.2 regarding class variable access via expression name
- JLS 15.11 regarding static field access via null references
这篇关于枚举的实例默认情况下是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!