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.