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
Join The Discussion
Comments ( 3 )
A. The process of acquiring properties and behaviors of one class by another
B. The process of creating objects
C. The process of encapsulation
D. The process of overloading methods
In Java, which keyword is used to implement inheritance between classes?
A. inheritsFrom
B. inherits
C. implements
D. extends
A. The class that inherits properties and behaviors
B. The child class
C. The class that is inherited from
D. The class that is marked as "final"
In Java, can a subclass inherit constructors from its superclass?
A. Only if the subclass is marked as "final"
B. Yes, a subclass inherits constructors from its superclass
C. Only if the superclass is marked as "static"
D. Only if the subclass is marked as "final"
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..