What is the result of compiling and running this program?
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 Test{
public static void main(String[] args){
Mammal h = new Horse();
Cattle c = new Horse();
c.eat(h);
}
}
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 Test{
public static void main(String[] args){
Mammal h = new Horse();
Cattle c = new Horse();
c.eat(h);
}
}
A. prints "Mammal eats food"
B. prints "Cattle eats hay"
C. prints "Horse eats hay"
D. Class cast Exception at runtime.
E. None of these
Answer: Option A
When class Cattle extends class Mammal, then the method eat() is not overrided but overloaded. That means the class Cattle now has two method :
1-> eat(Mammal m)
2-> eat(Cattle c)
Similarly when Horse extends Cattle, then the method are not over ridden because of the different signature i.e. different parameters.
So when c.eat(h) is called then c is referencing to Horse object so we look in Horse class.. where we find three method..
1-> eat(Mammal )
2-> eat(Cattle )
3-> eat(Horse )
Now h is refererring to mammal, so eat(mammal) will be executed
here simply eat method called by passing h type parameter that is Horse so it will be bind with Horse class eat method beacuse method parameter is Horse type
Hello everyone. ..I m new in java..I want to ask that how to create object from 2 different class or can any one dicuss the above program specially " cattle c=new horse(); " they have usef cattle and horse both how can be..