Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are instances of enums static by default?

Tags:

java

enums

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?

like image 961
ziggy Avatar asked Nov 25 '11 18:11

ziggy


People also ask

Are enums always static?

As enums are inherently static , there is no need and makes no difference when using static-keyword in enums . If an enum is a member of a class, it is implicitly static.

Is enum by default static?

Every enum constant is static.

Are enums public by default?

Syntax. Optional. Specifies that the Enum type is visible throughout the project. Enum types are Public by default.

Are enums implicitly static and final?

An enum type is implicitly final unless it contains at least one enum constant that has a class body. It is a compile-time error to explicitly declare an enum type to be final. Nested enum types are implicitly static.


2 Answers

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
like image 66
Dave Newton Avatar answered Oct 28 '22 18:10

Dave Newton


Yes, enums are effectively static.

like image 22
Almo Avatar answered Oct 28 '22 16:10

Almo