Forums Register Login

polymorphism

+Pie Number of slices to send: Send
class Mammal{
void eat(Mammal m){
System.out.println("Mammal eats food");
}
}
class Cattle extends Mammal{
void eat(Cattle c){
System.out.println("Cattle eats hay");
}
}
class Horse extends Cattle{
void eat(Horse h){
System.out.println("Horse eats hay");
}
}
public class Mm{
public static void main(String[] args){
Mammal h = new Horse();
Cattle c = new Horse();
c.eat(h);
}
}
Why is the output
"Mammal eats food" ?
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ]
Now I am super curious what sports would be like if we allowed drugs and tiny ads.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 802 times.
Similar Threads
explain the flow of the program
Doubt in the output of this program.
Inheritance doubt
Output........?
output
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 10:37:56.