简体   繁体   中英

How to prevent abstract method from being called?

I have a super super (grandparent) abstract bean class calling loadData() method in its init() method like this:

public abstract class BaseFwkPageController extends PageControllerSupport {

    public String init(){
        cleanSession();
        loadData();
        return initNavigation;
    }

    public abstract void loadData();

    // ...
}

now I don't want this loadData() method to be called in the sub subclass (child). I can't change the super class. How can I achieve this?

Override the method and give the new behavior to the child class. You could just

@Override 
public void loadData() {
    // do nothing.
}

You can't hide the method, reduce its visibility or prevent anyone from calling.

However you can do something like this in your subclass:

@Override
public void loadData() {
  throw new UnsupportedOperationException("not supported");
}

Alternatively, you could put in an interface , exposing only what may be called through the interface.

Interface interface = new Implementation();
interface.callMethod();

This way you will have complete control.

You can't prevent the calling of the method in children, as the method is public. You could count every method invocation in a private instance variable, and throw an exception, if it has been called more than once (or how many times you expect).

Furthermore you need to mark the method as final so children can't override this method and change the behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM