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.