Method overriding

exercise No. 222

Q:

We consider the following inheritance hierarchy:

abstract public class Parent {
  public void print(){
    System.out.println("Parent");
  }
}
public class A extends Parent {
  @Override
  public void print() {
    System.out.println("A");
  }
}
public class B extends Parent {
  @Override
  public void print() {
    System.out.println("B");
  }
}

There is nothing wrong here syntactically. All classes do compile well and allow for e.g.:

void someMethod(Parent p) {
  p.print();
}

However some code here is completely unnecessary.

  1. Give an explanation.

  2. How would you correct the logical flaw without affecting runtime behaviour?

A:

  1. Class Parent class is abstract. Therefore we cannot create any instance of Parent. Due to runtime polymorphism Parent#print() will thus never be executed directly.

    Classes A and B both override Parent.print(). And both child classes do not call Parent.print() using super.print(). Thus Parent.print() will never be executed.

  2. Solution: Parent.print() should be declared abstract thus omitting its implementation:

    abstract public class Parent {
      abstract public void print();
    }

    Note

    We cannot simply omit Parent.print() altogether. Otherwise the p.print() call in someMethod(Parent p) would be impossible.