Skip to content
Advertisement

Why does the call to a parent class constructor not call the parent’s methods that are overriden in the child class?

As shown in the code below, given a superclass Parent with a method calculate() that is called in Parent‘s constructor, but also overriden in the class Child, why does the implicit call to Parent‘s constructor within Child‘s constructor not call Parent‘s calculate() instead of Child‘s calculate()?

class Parent {
    Parent() {
        calculate();
        System.out.println("Empty parent ctor.");
    }
    void calculate() {
        System.out.println("Parent calculating...");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("Empty child ctor.");
    }
    @Override
    void calculate() {
        System.out.println("Child calculating...");
    }
}

public class ParentConstructor {
    public static void main(String [] args) {
        Parent child = new Child();
    }
}

Output:

Child calculating...
Empty parent ctor.
Empty child ctor.

I would have thought that to correctly construct a Parent object, its constructor should always be called with its own method definitions?

Advertisement

Answer

The method in the parent will never be called by a child or subclass that overrides the method unless you explicitly call it with the super statement. That is because during a method call, which method(parent class or child class) is to be executed is determined by the object type.

This process in which a call to the overridden method is resolved at runtime is known as dynamic method dispatch.

class Child extends Parent {
    Child() {
        System.out.println("Empty child ctor.");
    }
    @Override
    void calculate() {
        super.calculate(); // calling parent implementation
        System.out.println("Child calculating...");
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement