Question: why doesn't "a.eat(new Horse()); " reference the Horse.eat(Horse) method in a polymorphic way ? in the same way as a.eat() references the Horse.eat() method polymorphically ? I was expecting to see the output "Horse eat - overloaded" [ June 10, 2008: Message edited by: robert stannard ]
Ask yourself, at the time of the call, what is "a" referencing? What does it point to? Has it changed since it was declared? Or does it still point to the same object? [ June 10, 2008: Message edited by: Bob Ruth ]
SCJP - 86% - June 11, 2009
Joined: Jun 02, 2008
Hi Bob, Thanks for your question. I believe that the "a" is still pointing to the "horse" reference from the initial assignment, so when you invoke "a.eat()" you get the "horse eat" message and I was expecting the same to happen for the overloaded call a.eat(Horse). I can't see why this isn't happening. Can you? Regards Rob.
I think it's because eat(Animal) is overloaded, the method called is decided at compile time. The eat(Horse) in Horse class is just an override of the already overloaded method and not a new overloaded method (I think). What I do know is because "a" reference type is Animal, it's method in Animal class which is invoked.
You can see this if you add a new method to the Horse class which takes a different arguments and try and call it using the "a" reference. You won't be able to because its referring to the Animal class.
Hope I'm making sense, its kinda late!!!
SCJP 5.0 - Passed
Joined: May 03, 2008
If you have K&B book check out page 108-109.
Joined: Jun 02, 2008
Thanks for your comment, I read those pages in K&B you mentioned and it seems like the "rule" is that polymorphism applies only to method overriding and not to overloading.
The method invoked in an overloaded method is determinded by the reference type whereas if the method is overriden then the Object type determines which method is called.
I think I understand it now. Thanks again for your help.
In your code Animal has two methods eat() and eat(Animal), Horse has two methods eat() and eat(Horse). Here Horse overring only one method eat(). eat(Animal) and eat(Horse) methods are overloading methods not overriding methods. So reference of Animal class 'a' can refer only eat(Animal).