Require override of method to call super

Viewed 12128

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?

8 Answers

For the Android Developers out there, you can simply use the @CallSuper annotation.

Sample:

public class BaseClass {
  @CallSuper
  public void myMethod() {
    //do base required thing
  }
}

On the overriding class:

public class OverridingClass extends BaseClass{

    @Override
    public void myMethod(){
        super.myMethod(); //won't compile if super is not called
        //do overring thing here
    }
}

AndroidX Solution:

Require super that throws compile error if not called in @Override method:

import androidx.annotation.CallSuper;

class BaseClassThatRequiresSuper {
    
    @CallSuper
    public void requireSuper() {
        
    }
}

class ChildClass extends BaseClassThatRequiresSuper {
    
    @Override
    public void requireSuper() {
        super.requireSuper();
    }
}

If ChildClass does not call super.requireSuper() it will give you a compile error. Saying :

Overriding method should call super.requireSuper

Related