• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static methods from a non static reference  RSS feed

 
jishnu dasgupta
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can you please explain to me why the following is valid in java.



As i have not initiallized instance varriable t, it must be null.So when i run this snippet, it prints the "I am a method". why is the null reference not creating a Runtime Exception when i am using it??
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The point is that you're not invoking a method on a reference because it is a static method. And because you're not invoking it on a reference, the reference is allowed to be null.
But invoking a static method on a reference instead of a classname is a very bad habit.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable t is not pointing to any instance (it holds a null reference), but t does have a type of "TestCode." Therefore, it's possible to access non-instance (static) members of TestCode using t, because t does not need to resolve to any particular instance.

As Wouter pointed out, using a variable rather than the class name to access a static member is poor form.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try thisIt is, as you have already been told, poor style, but it will both compile and run.
 
Nico Van Brandt
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would have thrown a NullPointerException if the method aMethod() would not have been static.

A static method means the same as "You dont need an instance of this Class to call me".
 
jishnu dasgupta
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all, got the picture.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nico Van Belle wrote: . . . A static method means the same as "You dont need an instance of this Class to call me".
It means more than that.
 
Nico Van Brandt
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure, I know that. That's just a simplified look on static methods.
But I figured.. he'll find out the restrictions and perhaps internal workings once he goes deeper into Java.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!