开发者

Java call a method 'inexplicitly'

开发者 https://www.devze.com 2023-03-07 11:24 出处:网络
If in an abstract base class, there is a public/private method m1 and an abstract method m2, how can I make the method m1 to be executed before the implemented method m2 in the subclass. (Basically I\

If in an abstract base class, there is a public/private method m1 and an abstract method m2, how can I make the method m1 to be executed before the implemented method m2 in the subclass. (Basically I'm t开发者_开发技巧rying to put some basic validations in m1)


In the base class you can put a method to be the entry point of you API for that method:

 public void mCaller() {
     m1();
     m2();
 }

Then use mCaller instead of calling m1 and m2 directly. You can also change visibility of m1 and m2 methods.


Something like this:

public abstract class Base {
    public boolean m1() {
        // validation stuff
    }
    public final void m2() {
        if (m1()) {
            m2Imp();
        }
    }
    protected abstract void m2Imp();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消