File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes why am i able to call a static method using an object of that class ... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "why am i able to call a static method using an object of that class ... " Watch "why am i able to call a static method using an object of that class ... " New topic
Author

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

Lalit Mehra
Ranch Hand

Joined: Jun 08, 2010
Posts: 384

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



http://plainoldjavaobject.blogspot.in
Martin Vanyavchich
Ranch Hand

Joined: Sep 16, 2008
Posts: 241
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!




SCJP 6, OCMJD 6, OCPJWSD 6
I no good English.
Lalit Mehra
Ranch Hand

Joined: Jun 08, 2010
Posts: 384

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

Joined: Sep 16, 2008
Posts: 241
Yes, that would sum it up
Lalit Mehra
Ranch Hand

Joined: Jun 08, 2010
Posts: 384

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

Joined: Mar 05, 2008
Posts: 3003
    
    9
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

Joined: Jun 08, 2010
Posts: 384

ya Mike even i feel the same
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why am i able to call a static method using an object of that class ...
 
Similar Threads
overriding method question and a super question.
The Ducks are back
Reference variable
Polymorphism
Creating Objects