10
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?

AHHP
  • 2,967
  • 3
  • 33
  • 41
ziggy
  • 15,677
  • 67
  • 194
  • 287

2 Answers2

23

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

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
6

Yes, enums are effectively static.

Almo
  • 15,538
  • 13
  • 67
  • 95