ExamVeda
Login
Home
This question belongs to Java Program Inheritence
Inheritence
?

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);
      }
}

Answer & Solution
Correct Answer: Option A
Let's discuss the solution. Join the discussion
Examveda
Question posted by Examveda
Community

Join the Discussion

3 Comments
Abhishek Chaudhary
Abhishek Chaudhary 9 years ago
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
Mahendra Birla
Mahendra Birla 10 years ago
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
Rahul Ranjan
Rahul Ranjan 10 years ago
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..