This is what I’m trying to do:
class A {
void myMethod() {
// execute A
}
}
class B extends A {
void myMethod() {
// execute B
}
}
class C extends B {
void myMethod() {
// execute C
// execute myMethod in A, without touching myMethod in B OR both
}
}
I’d like to do this conditionally, that is sometimes call what’s in myMethod inside B and other times not, but always call myMethod inside A.
By calling super.myMethod() in C I get myMethod of B, but I only want myMethod of A. Is that possible? I’ve heard of “virtual” things, but I don’t know how to use them… yet.
No, it is not possible in Java on purpose. Class
Boverrides and therefore hides the implementation ofmyMethodinAfrom further deriving classes. AllowingCto callmyMethodofAwould violate this encapsulation. Consider a case whereB.myMethodperforms some updates before internally callingA.myMethodwhich are important for the correct functionality ofB. Without these updates, the contract ofBcould be violated. Therefore, it should not be possible to callA.myMethodin a derived class without callingB.myMethod.Usually, your design is flawed if you want to do stuff like this.
Of course, you can do stuff like suggested by Dave in the comments: You can alter the implementation of
B.myMethodto callA.myMethod. This is okay, becauseBretains the control over when to callA.myMethod. Therefore, it can take care that its contract is not violated.Another idea is to factor out the behaviour you want from
Ainto another method and call this one.