Solenoid
Solenoid

Reputation: 2381

Java: calling the base method class from a second derived class

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.

Upvotes: 2

Views: 412

Answers (3)

Eddie D
Eddie D

Reputation: 349

While I agree with most answers about possibly changing the design, to directly answer you could pass in a variable boolean into the first method. The entirety of the logic in B's method should depend on a conditional if statement depending on the boolean. Make sure to make a call to super.myMethod() outside of this if statement.

Something like this:

void myMethod(boolean execB) {
// execute B
super.myMethod(execB);
    if(execB)
    {
        //B logic
    }
}

This is however, not the best in practice, because only B's method is using the variable, hence why refactoring the design might be a good decision.

Upvotes: 0

gexicide
gexicide

Reputation: 40058

No, it is not possible in Java on purpose. Class B overrides and therefore hides the implementation of myMethod in A from further deriving classes. Allowing C to call myMethod of A would violate this encapsulation. Consider a case where B.myMethod performs some updates before internally calling A.myMethod which are important for the correct functionality of B. Without these updates, the contract of B could be violated. Therefore, it should not be possible to call A.myMethod in a derived class without calling B.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.myMethod to call A.myMethod. This is okay, because B retains the control over when to call A.myMethod. Therefore, it can take care that its contract is not violated.

Another idea is to factor out the behaviour you want from A into another method and call this one.

Upvotes: 3

Aaron Digulla
Aaron Digulla

Reputation: 328594

If you need this, A.myMethod() probably does too much. Try to refactor it into several smaller methods with access level protected.

That allows you to call these methods from both B and C.

Upvotes: 0

Related Questions