Reputation: 131
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
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 :
Upvotes: 1