Examveda
Examveda

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

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


This Question Belongs to Java Program >> Inheritence

Join The Discussion

Comments ( 3 )

  1. Abhishek Chaudhary
    Abhishek Chaudhary :
    7 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

  2. Mahendra Birla
    Mahendra Birla :
    7 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

  3. Rahul Ranjan
    Rahul Ranjan :
    8 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..

Related Questions on Inheritence

What is inheritance in Java?

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