• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why am i able to call a static method using an object of that class ...

 
Lalit Mehra
Ranch Hand
Posts: 384
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why am i able to call a static method using an object of that class ... when it can only be called using the classname.methodName() format

 
Martin Vanyavchich
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java looks up what type this object is (how it is declared) and calls that classes static function. Callig a static function on an object reference type works, but it's ... let's say bad coding. You could end up with somewhat upredictable results. See example below. Both objects in memory are actualy ducks, but it outputs

quack! quack!
sound! sound!


 
Lalit Mehra
Ranch Hand
Posts: 384
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well ok ...

this means although we can use an object reference to call a static method we should not because in case we use polymorphic forms of reference variables that could create confusion ... i suppose this is all that you meant my friend
 
Martin Vanyavchich
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that would sum it up
 
Lalit Mehra
Ranch Hand
Posts: 384
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmmm ... even i was like "feeling the same" but as the book said you can only call a static method the classname.methodName() way so i went on to check it ...

thanks buddy ...
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lalit Mehra wrote:the book said you can only call a static method the classname.methodName() way

If a book said that, the book is definitely wrong.

Is it possible that the book said you should only call a static method that way? Because that's a matter of opinion, but it's an opinion I and many others agree with.
 
Lalit Mehra
Ranch Hand
Posts: 384
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya Mike even i feel the same
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic