Hi there: On the surface it looks like that eat() is over- ridden in sub-classes. In fact it is not, as the argument signature is differenct in each sub-class. So method eat(Mammal m) is inherited in the cattle class and it is called by c. Hope this helps Thanks Barkat
Each of your eat() methods has a different argument list, so you are not overriding, you are overloading. Do you realize that each instance method automatically gets a variable called "this", which is a reference to the object that invoked it? You most likely don't really want to have an argument to eat() at all.
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
posted 16 years ago
I am still a bit confused. Isn't 'c' an object of Horse so won't 'c.eat(h)' call 'eat()' on horse ? and in the same vien isn't 'h' an object of horse ? Sorry i am getting a bit confused here Thanx for the help
Hi Soum, The question's a bit tricky. What you said was actually my first answer. At compile-time: h -> Mammal c -> Cattle Runtime: h -> Horse c -> Horse Since Java knows h to be an instance of Mammal at compile-time, no matter what the class of the object it holds at runtime, the method eat(Mammal) will be called. Also, note that c, being declared as of class Cattle, cannot call eat(Horse). This is because the methods are overloaded, not overriden.
posted 16 years ago
Hi Soum: Let us take from beginning. Method eat(Mammal M) is NOT over-ridden by Method eat(Cattle c) because eat(Mammal M) has different argument than eat(Cattle c). Therefore, eat(Mammal M) is inheritated in sub-class Cattle. Same is the story between eat(Cattle c) and eat(Horse h). Ultimately, eat(Mammal M) is inherited in Horse class. Now c.eat(H) is called. Note that H is of Mammale type but holds Horse object. Because we are passing Mammale type parameter, the inherited eat(Mammal M) in c object is invoked. Hence, it prints what it prints... [ August 19, 2002: Message edited by: Barkat Mardhani ]
He's dead Jim. Grab his tricorder. I'll get his wallet and this tiny ad:
how do I do my own kindle-like thing - without amazon