Lets say 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();
Will print:
Base: methodA
Derived: methodB
Derived: methodA
My question is: Is it possible to force d.methodA()
to use Base.methodB()
? I want the code to print out:
Base: methodA
Base: methodB
Derived: methodA
For those knowledgable in C++, this could be done with something like Base::methodB()
in the Base
class. Is there an equivalent in Java?
I am almost sure this has been asked before, but I was unable to find anything, I'm sorry if this is a duplicate.
A base class is a class, in an object-oriented programming language, from which other classes are derived. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class (except constructors and destructors).
Base baseRef = new derived(); // Due to dynamic binding, will call the derived class // display() function baseRef. display(); Base baseRef = new derived(); // Due to dynamic binding, will call the derived class // display() function baseRef. display();
Hierarchical Inheritance In Java A class can have more than one class derived from it. So we have one base or superclass and more than one subclasses. This type of inheritance is called “Hierarchical inheritance”.
If a method in the base class can have an override, and the derived class has provided one, there is no way to force a call to the method of the base class.
If the base class needs to call the functionality in the base class, it can put it into a separate method, and declare it final
. Then it could make a decision between its own implementation and the derived implementation like this:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With