Static enum constants

3
    enum Animals {
     DOG("woof"), CAT("meow"), FISH("burble");
     String sound;
     Animals(String s) { sound = s; }
     }
     class TestEnum {
      static Animals a;
      public static void main(String[] args) {
      System.out.println(a.DOG.sound + " " + a.FISH.sound);
     }
   }

I do not understand why the above code compiles normally. The enum type constant "Animals" is declared without any initialization, should not a nullpointer exception occur? Does not this occur because it is declared static? How does this occur?

    
asked by anonymous 15.12.2015 / 01:11

2 answers

4

It would give NullPointerException if it was a.sound .

It's strange, but by doing a.DOG.sound you're accessing DOG statically as Animals.DOG.sound .

In general, Java allows you to access static members, attributes, or methods through variables in an instance. An enum is just a more specific case where each constant works a static attribute.

Similarly, for example, MinhaClasse.metodoEstatico() can also be executed with meuObjeto.metodoEstatico() , even when meuObjeto = null .

Java, knowing the type of the variable, can identify the static member and execute. Since it does not need this to reference the instance, NullPointerException does not occur.

In practice:

class PegadinhaDeCertificacao {
    static void metodo() {
        System.out.println("Ha! Pegadinha do Malandro!!");
    }
    public static void main(String... args) {
        Test a = null;
        a.metodo();
    }
}

The code above will print the text normally and will not throw any exceptions.

Again, it is counter-intuitive behavior, so it is not recommended to access static members using instance variables .

Good IDEs and code analyzers will issue alerts when encountering such situations.

    
15.12.2015 / 02:28
2

As per the Oracle link documentation , an enumerator has no instances beyond those defined by its constants.

In a response in English OS, each enum class is compiled as sublcasse of java.lang.Enum , and each constant becomes static final .

In the command line, you can execute the line javap -p -c NomeDaClasse , as the ClassName for your .class file.

Another documentation link for reference: Enum Types

    
15.12.2015 / 01:43