Are instances of enums static by default?

前端 未结 2 1424
醉酒成梦
醉酒成梦 2021-02-14 12:43
enum Animals{
    DOG(\"woof\"),
    CAT(\"Meow\"),
    FISH(\"Burble\");

    String sound;

    Animals(String s) {
            sound = s;
    }
}
public class TestEnu         


        
2条回答
  •  余生分开走
    2021-02-14 13:40

    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

提交回复
热议问题