Force use of a base class method in Java

你离开我真会死。 提交于 2020-05-08 07:17:28

问题


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.


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/23484767/force-use-of-a-base-class-method-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!