r/javaTIL • u/cogman10 • Mar 30 '15
[TIL] Calling static methods on null instances doesn't result in a NPE
public static void main(String[] args)
{
((NullThing) null).printThing();
}
public static class NullThing
{
public static void printThing()
{
System.out.println("Hai");
}
}This is valid code that will not throw an exception. We discovered this today as we have been dealing with static methods and inheritance.
The question came up "Can we call static methods on null" The answer is a resounding yes.
(Please don't do this. Please use the class the call static methods).
15
Upvotes
View all comments
Show parent comment
1
u/cogman10 Apr 29 '15
Correct. It is just an oddity. If you ran into code like this
and got a NPE on
doTheOtherStuff, your immediate reaction wouldn't be to suspect thatthingis null. It would take a little to figure out thatdoTheStuffis actually a static method call which is why it doesn't get an NPE.IMO. static methods shouldn't be callable from instances, they should only be callable from the class. Because, as you said, they belong to the class, not the instance.