Y.E.
Y.E.

Reputation: 922

Overridden method call in parent method

Considering the following:

public class Child extends Parent{
  public boolean isMeh(){
    return true;
  }

  public void childMethod() {
    System.out.println("child: "+isMeh());
  }

  public static void main(String... args){
    Child child = new Child();
    child.parentMethod();
    child.childMethod();

  }

}

class Parent{
  public boolean isMeh(){
    return false;
  }

  public void parentMethod() {
    System.out.println("parent: "+isMeh());
  }
}

Output:

parent: true
child: true

It is pretty obvious when isMeh() is called within Child class, it calls the overridden method.

But when the overriden method is called within a method of the parent object, it still calls the child object's method.

I see that we create one child object and parentMethod is just inherited so when we call isMeh() it calls the available(overridden) one.

What would be the reason for this implementation in java?

Upvotes: 3

Views: 3010

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

Any class in an inheritance hierarchy of Parent, be it a Child, a Parent, or some Grandchild deriving from them, has exactly one implementation of the method called isMeh. When Child overrides isMeh of Parent with its own implementation, it replaces the implementation; as far as the Child is concerned, the implementation in the Parent no longer applies*.

When you instantiate Child and call its parentMethod, the method has access to only one method isMeh - that is, the implementation provided by the Child. That is why you get the behavior that you describe.

This behavior allows for very nice patterns: for example, you can write a "partial implementation" of a method in the parent by relying on "plug-in" functionality in the child class provided through overrides. This technique is known as Template Method Design Pattern.

* although Child retains an ability to call Parent's isMeh explicitly.

Upvotes: 1

Related Questions