枚举的实例默认是静态的吗?

发布于 2024-12-18 05:17:12 字数 456 浏览 2 评论 0原文

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

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

发布评论

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

评论(2

罪#恶を代价 2024-12-25 05:17:12

枚举是隐式的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

瑾兮 2024-12-25 05:17:12

是的,枚举实际上是静态的。

Yes, enums are effectively static.

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