Alex Rivera | Logout

How do I force a polymorphic call to the super method?

Asked 2011-05-26T17:15:38.223
13

I have an init method that is used and overridden through out an extensive heirarchy. Each init call however extends on the work that the previous did. So naturally, I would:

@Override public void init() {
   super.init();
}

And naturally this would ensure that everything is called and instantiated. What I'm wondering is: Can I create a way to ensure that the super method was called? If all of the init's are not call, there is a break down in the obejct, so I want to throw an exception or an error if somebody forgets to call super.

TYFT ~Aedon

Edit
Report

1 Answer

9

Here's one way to raise an exception if a derived class fails to call up to the superclass:

public class Base {
    private boolean called;
    public Base() { // Doesn't have to be the c'tor; works elsewhere as well.
                    // In fact, shouldn't call overridable methods from c'tor.
        called = false;
        init();
        if (!called) {
            // throw an exception
        }
    }
    protected void init() {
        called = true;
        // other stuff
    }
}
answered 2011-05-26T17:35:35.967

Your Answer