Question

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.

Was it helpful?

Solution

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();
    }
}

OTHER TIPS

Can't do it. In C++-speak, 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");
    }
}

I think you can achieve what you want by breaking out the functionality in the parent class into it's own method like so. Not the direction you were looking in but achieves 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");        
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top