• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can a call to a static method made if its Object is pointing to null  RSS feed

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

could anybody please clarify me this :

Can a call to a static method made if its Object is pointing to null


Why this method is not throwing NullPointerException?
 
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When the compiler sees a reference (like t) used to call a static method (like sleep()), all it looks at is the declared type of the reference variable. Since t is a Thread, t.sleep(20) is considered exactly equivalent to Thread.sleep(20). The actual value at runtime (which the compiler doesn't know) is completely ignored. Yeah, it's weird. But that's the way the rules were written, back when Java began.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As for "is this acceptable?" - it's acceptable to the compiler, yes. And it will run with no problems. But I think it's a bad practice for a programmer to write code like that, precisely because it's confusing to many people. I and many others think it would have been better if it were illegal to call a static method using a reference to an instance. Just use the class name instead. It's much clearer to readers. However, this is just a style guideline, and not everyone will agree. As far as the compiler and JVM are concerned, you can write t.sleep() if you want to; it's fine. It's only humans who may object to the practice.
 
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just had to pop in and say "Great answer Mike!"
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!