Calling a super method from a super class

As an example of a brain twist, my professor gave us the following exercises to learn about inheritance. We needed to find out the result.

//java public class A { public void f() { System.out.println("A -> f()"); x = x + 4; if (x < 15) this.f(); //the f-call } public int x = 5; } public class B extends A { @Override public void f() { System.out.println("B -> f()"); x = x + 3; super.f(); } } public class Main { public static void main(String[] args) { A a = new B(); System.out.println("af()"); af(); System.out.println(ax); } } 

The way out, as I expected

  • af ()
  • B β†’ f ()
  • A β†’ f ()
  • B β†’ f ()
  • A β†’ f ()
  • 19

However, now it has become interesting to me. Is there a way to make an f call to call method f in A, even if I use it from a B object, similar to how I call f from A to B using super.f (). Thus, the output will become (I think):

  • af ()
  • B β†’ f ()
  • A β†’ f ()
  • A β†’ f ()
  • 16

Is it possible? And if so, how?

Note. I'm not sure what the practical application of this will be, I'm just trying to learn something new: P

+5
source share
2 answers

The short answer is no, you cannot do this.

The longer answer is that it will violate all kinds of guarantees of inheritance. Your class B essentially said: "Now I am providing a canonical method for public void f() ." Since B provides the specified method, it is allowed to return to the parent to use it (and something very useful).

If A was allowed to do the same, it would essentially be a workaround for the behavior that B wants to override.

There are many templates available that give you similar behavior, for example. Pattern template

+5
source

Since polymorphism will be applied to all methods of the superclass object, f that will be called will always be the type of the execution object - in this case B , therefore the method B f will always be called. This cannot be changed in Java.

You can get around this by doing the work of the A f method in the private method, say foo , so that when f is called, foo is called repeatedly. In A :

 public void f() { foo(); } private void foo() { System.out.println("A -> f()"); // Lie. x = x + 4; if (x < 15) this.foo(); //the "f"-call } 
+2
source

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


All Articles