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
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.
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).