Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require override of method to call super

Tags:

java

super

I want that when a child class overrides a method in a parent class, the super.method() is called in that child method.

Is there any way to check this at compile time?
If not, how would I go about throwing a runtime exception when this happens?

like image 784
Andrew Gaspar Avatar asked Jul 28 '11 02:07

Andrew Gaspar


People also ask

Can override method call super?

A subclass can override methods of its superclass, substituting its own implementation of the method for the superclass's implementation.

How do you call a superclass version of an overridden method?

Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).

How do you use super overriding?

If both parent & child classes have the same method, then the child class would override the method available in its parent class. By using the super keyword we can take advantage of both classes (child and parent) to achieve this. We create an object of child class as it can inherit the parent class methods.


1 Answers

There's no way to require this directly. What you can do, however, is something like:

public class MySuperclass {     public final void myExposedInterface() {         //do the things you always want to have happen here          overridableInterface();     }      protected void overridableInterface() {         //superclass implemention does nothing     } }  public class MySubclass extends MySuperclass {     @Override     protected void overridableInterface() {         System.out.println("Subclass-specific code goes here");     } } 

This provides an internal interface-point that subclasses can use to add custom behavior to the public myExposedInterface() method, while ensuring that the superclass behavior is always executed no matter what the subclass does.

like image 177
aroth Avatar answered Sep 20 '22 22:09

aroth