Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override method to invoke superclass' superclass method? [duplicate]

Part of me thinks that this shouldn't be possible (even if it is), but I'll ask anyway.

Given the following class hierarchy (Grandparent and Parent are from a 3rd party and thus, not under my control), how would I override myMethod() in Child such that it bypasses the overridden implementation in Parent and invokes the one in Grandparent?

class Grandparent {
   public void myMethod() {
      // do stuff
   }
}

class Parent extends Grandparent {
   @Override public void myMethod() {
      super.myMethod();
      // do something else
   }
}

class Child extends Parent {
   @Override public void myMethod() {
      // ??? I want to *only* do what Grandparent did here
   }
}

Pretend that the Parent class provides a lot of other helpful behavior and is a crucial element of Child's hierarchy (in other words, I'm not looking for "make Child a subclass of Grandparent".

like image 389
Steve Reed Avatar asked Dec 04 '22 15:12

Steve Reed


1 Answers

The idea behind inheritance is that each class defines their methods how they need, so you don't need to be inspecting any code.

It seems like you're subclassing here just to re-use code, and that's not the idea of subclassing.

Maybe you should have a helper member to do some of the tasks you need, instead of subclassing, and have both "Child" and "Parent" classes extend "Grandparent".

The main question you need to ask yourself is: "Is Child really a descendant of Parent, Grandparent or neiter?" In other words, for every instance of Child, can I say it's a Parent?

If the answer is no, then you're subclassing wrongly: inheritance is supposed to mean something, not just code re-use (i.e. Ford IS ALSO a Car, not just "Ford" uses "Car" methods).

like image 146
Seb Avatar answered Dec 26 '22 10:12

Seb