Wednesday, 20 September 2017

Statics in Java - Answer

The output of the program in Statics in Java:
/opt/tools/java/jdk1.8.0_60/bin/java com.mrbear.Test1
Mount Monadnock

So why don't we get a NullPointerException, which most people would expect?

As indicated in the JLS 15.12.4.11, static methods are directly called on the Class, not on the Object, so the presence or absence of the object is entirely irrelevant.

This is one of the most compelling reasons for always using the Class to call static methods on instead of the Object. It prevents ambiguity for us poor software developers.

P.S. When you think about it, "null" in Java is actually a bit weird, as it can be forcibly cast to any java Object.

References

[1] The Java Language Specification, Java SE 8 Edition
https://docs.oracle.com/javase/specs/jls/se8/jls8.pdf

No comments:

Post a Comment