File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Polymorphism" Watch "Polymorphism" New topic


mukhan myrzakulov

Joined: Jan 16, 2008
Posts: 13
Hi, I am confused with POLYMORPHISM in overloaded and overriden methods. So, as I understood, Java doesn't give you polymorphism when you use overloading. For example,

Can't understand why it does it? Why not to use polymorphism...

Next example:

So I am confused why java sometimes uses polymorphism and sometimes not?

Thank you I appreciate your help.

Edit by mw: Added Code Tags.

[ June 06, 2008: Message edited by: marc weber ]
Noam Wolf

Joined: Jul 29, 2007
Posts: 12
Hi Mukhan,

It looks like you are confusing overloading and overriding. Remember the main rules:

OVERRIDING - Must have same argument list and return type (or covariant return)

OVERLOADING - Reusing a method name but with different arguments which may have different return types if argument lists are also different

So now that we've established that, let's take another look at your first example:

What do you think that is? It's on OVERLOAD, same name and return type BUT different parameters.

So, in this case you are calling eat() twice, once with an Animal and once with a Horse BUT they are BOTH an Animal Reference (the stuff on the left of the assignment) and the rule for overloading is the the reference type determines what gets called... so if you actually try to run your code you'll see that it prints "Animal is eating!!" TWICE!! where did you get your result from?

Now the second example is an OVERRIDE because you define the eat() method in Animal and then Horse OVERRIDES this method (same arguments and return type) and the rules of overriding are determined by the Object type (the right side of the assignment) so will print "Horse is eating" BUT eat(string) is an OVERLOAD and it is determined by the reference type, which in your case is Animal... and since Animal doesn't have that overload the compiler will complain. If you change:


your code will compile.

Hope that helps
marc weber

Joined: Aug 31, 2004
Posts: 11343

See How my dog learned polymorphism.

(And please use Code Tags when posting code.)

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
priya shende

Joined: Mar 17, 2008
Posts: 20
Thanks Noam.Nice Explanation.
mukhan myrzakulov

Joined: Jan 16, 2008
Posts: 13
Thanks man, great explanation! I appreciate your help!
I agree. Here's the link:
subject: Polymorphism
It's not a secret anymore!