Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 686
Brian Avatar asked May 23 '11 04:05

Brian


People also ask

How do you call the super class method from child class?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

Can we call super in method?

2) super can be used to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.

What is superclass method?

The superclass method is used to access the parent class inside a child class. This method has a variety of uses when inheriting parent members.

Can we call super super method in Java?

The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.


1 Answers

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
    }

}
like image 69
Tom Avatar answered Nov 04 '22 07:11

Tom