Search code examples
javainheritancesuperclass

Enforce super call on non constructor methods


Is it possible to enforce an overriden method to call the superclass method? Constructors always need to call their superclass constructor. But i want to enforce this on normal methods, without the position of when it is called mattering.

Example:

public class A {

    public void doSth() {
        System.out.println("I must appear on console!");
    }

}

public class B extends A {

    @Override
    public void doSth() {
        System.out.println("Bla!");  // IDE should mark an error, because supermethod is not called.
    }

}

Solution

  • Although not strictly Java related, I was looking for an answer to this issue as it relates to Android and found the annotation in the support annotations library called "@CallSuper". It does exactly what you think, and throws a lint error if the subclass does not call the super's implementation of methods annotated with @CallSuper.

    That solved my usecase, but again, I know that the solution is strictly tied with Android. Please let me know if that is too far off base and I will remove the answer.

    Here is some more documentation on @CallSuper. https://developer.android.com/reference/android/support/annotation/CallSuper.html https://developer.android.com/studio/write/annotations.html (just search for CallSuper and it'll show right up in that second link.