Forcing a base class method in Java

Suppose I have two classes Base and Derived :

 public class Base { public Base() { } public void methodA() { System.out.println("Base: methodA"); methodB(); } public void methodB() { System.out.println("Base: methodB"); } } public class Derived extends Base { public Derived() { } public void methodA() { super.methodA(); System.out.println("Derived: methodA"); } public void methodB() { System.out.println("Derived: methodB"); } } 

Now with this:

 Base d = new Derived(); d.methodA(); 

It will be printed:

 Base: methodA Derived: methodB Derived: methodA 

My question is: Is it possible to force d.methodA() use Base.methodB() ? I want the code to print:

 Base: methodA Base: methodB Derived: methodA 

For those who are known in C ++, this can be done using Base::methodB() in the Base class. Is there an equivalent in Java?

I am pretty sure that this was asked before, but I could not find anything, sorry if this is a duplicate.

+8
java inheritance
source share
3 answers

If the base class method can have an override, and the derived class provides one, then there is no way to force the base class method to be called.

If the base class needs to call functionality in the base class, it can put it in a separate method and declare it final . Then he could make a decision between his own implementation and the derivative implementation as follows:

 public class Base { public Base() { } public void methodA() { System.out.println("Base: methodA"); // Call the derived method methodB(); // Call the base method methodB_impl(); } public final void methodB_impl() { System.out.println("Base: methodB"); } public void methodB() { methodB_impl(); } } 
+6
source share

Impossible to do this. In C ++, they say that all Java methods are "virtual." So do this instead:

 public class Base { public void methodA() { System.out.println("Base: methodA"); baseMethodB(); } public void methodB() { baseMethodB(); } private void baseMethodB() { System.out.println("Base: methodB"); } } 
0
source share

I think you can achieve what you want by tearing the functionality of the parent class into your own method. Not the direction you were looking in, but reaching what you want:

 public class Base { public Base() { } public void methodA() { System.out.println("Base: methodA"); methodBInner(); } public void methodB() { methodBInner(); } private void methodBInner() { System.out.println("Base: methodB"); } } 
0
source share

All Articles