How to override the method to call the superclass "superclass"?

Part of me thinks that this should not be possible (even if it is), but I will ask anyway.

Given the following class hierarchy ( Grandparentand Parentbelong to a third party and therefore not under my control), how would I override myMethod()in Childso that it bypasses the overridden implementation in Parentand calls the one that is 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
   }
}

Imagine that a class Parentprovides many other useful actions and is a key element of the hierarchy Child(in other words, I'm not looking for a “make Childsubclass Grandparent”.

+3
source share
4

, , , - .

, , .

, , , , , "Child" "Parent" "Grandparent".

, : " - , ?" , Child, , Parent?

, : -, (.. Ford IS ALO a Car, "" "" ).

+10

, Parent Grandparent , , (, -, ) :

"" ( , , ) myMethod(). , , myMethod() / , "" "".

, , , , , . / myMethod() , . , .

Seb, , . . - .

+3

.

final . ( ) .

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

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
      myHelperMethod();
   }
}
+2

?

, (myNewMethod) , myMethod , myNewMethod Child?

( Java, , )

class Grandparent {
   public void myMethod() {
      myHelperMethod();
   }
}

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

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

Source: https://habr.com/ru/post/1706056/


All Articles