How do I make sure a super method is called in a child?

Brian picture Brian · May 23, 2011 · Viewed 7.9k times · Source

If I have the method public void send() { /* some code */ } in a class and have a child of this class also have a method public void send() { /* some code*/ }, how do I ensure that the child must call super.send() somewhere in the send() method that it's trying to override?

I was wondering about this because I've written in APIs where if you don't call the super of that method when overriding it, it'll throw an exception telling me that I haven't called the super method. Is this hard coded or can this be done with some keywords in Java?

Answer

Tom picture Tom · May 23, 2011

You can't really, but you can...

class MySuperClass {
    public final void send() {
        preSend();
        // do the work...
        postSend();
    }

    protected void preSend() {
        // to be overridden in by sub classes
    }

    protected void postSend() {
        // to be overridden in by sub classes
    }

}