CuriousIndeed
CuriousIndeed

Reputation: 131

Rationale for superclass reference to subclass object calls overriden method in subclass

Example taken from here

class Human{  
   //Overridden method  
   public void eat()  
   {  
      System.out.println("Human is eating");  
   }  
}  
class Boy extends Human{  
   //Overriding method  
   public void eat(){  
      System.out.println("Boy is eating");  
   }  
   public static void main( String args[]) {  
      Boy obj = new Boy();  
      //This will call the child class version of eat()  
      obj.eat();  
   }  
}  

If we now create an Boy object with Human reference as:

Human boy = new Boy();

and call

boy.eat()

Why does it call eat() from Boy class rather than eat() from Human class. I know that methods from Boy class cannot be used when Human reference variable is used. So why does boy.eat() not call eat() from Human class?

Upvotes: 0

Views: 57

Answers (1)

Zrop
Zrop

Reputation: 11

Because boy is a reference variable of type Human whose value is an object of type Boy.

Human boy; // create a reference variable of type Human
boy = new Boy(); //  whose value is an object of type Boy

The right method to call is decided at runtime according to the object referred to :

  • Compiler knows the type of boy is Human, so it checks Human has a eat() method
  • At runtime, JVM discovers the value of boy is new Boy(), so it calls eat() method of Boy

Upvotes: 1

Related Questions