Static constants

Asked

Viewed 223 times

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 "Animals" constant is declared without any initialization, shouldn’t a nullpointer exception occur? Does this not occur because it is declared static? How does this occur?

2 answers

4


Daria NullPointerException if it were a.sound.

It’s strange, but in doing a.DOG.sound you are accessing DOG statically as if it were Animals.DOG.sound.

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

In the same way, 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. As it does not need the this to reference the instance does not occur NullPointerException.

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 above code will print the text normally and will not throw any exception.

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

Good Ides and code analyzers will issue alerts while encountering such situations.

2

According to the link of the Oracle documentation, an enumerator has no more instances than those defined by its constants.

In a reply in the English OS, each Enum class is compiled as subfloors of java.lang.Enum, and each constant becomes static final.

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

Another link in the documentation for reference: Enum Types

Browser other questions tagged

You are not signed in. Login or sign up in order to post.