Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
    }

}
like image 552
Torhan Bartel Avatar asked Feb 05 '26 12:02

Torhan Bartel


1 Answers

No, that is not possible. It is entirely up to the overriding method to call the superclass method, or not.

However, there is a way to do it, if you want to enforce control.

This is called the Template Method Pattern. Whether the template methods are abstract or stubs (like shown here), depends on whether they must do something, or simply allow something extra to be done.

public class A {
    public final void doSth() { // final, preventing override by subclasses
        beforeDoSth();
        System.out.println("I must appear on console!");
        afterDoSth();
    }
    protected void beforeDoSth() { // protected, since it should never be called directly
        // Stub method, to be overridden by subclasses, if needed
    }
    protected void afterDoSth() {
        // Stub method, to be overridden by subclasses, if needed
    }
}

public class B extends A {
    @Override
    protected void afterDoSth() {
        System.out.println("Bla!");
    }
}

If you then execute new B().doSth(), you'll get:

I must appear on console!
Bla!
like image 171
Andreas Avatar answered Feb 07 '26 00:02

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!