Search code examples
javainterfaceoverriding

Disabling derived classes from overriding interface method


public interface Interface {
    void interfaceMethod();
}
        
abstract class Base implements Interface {
    @Override
    public void interfaceMethod() {
        baseClassMethod();
        abstractMethod();
    }

    private void baseClassMethod() {
        System.out.println("Base implementation");
    }

    protected abstract void abstractMethod();

}
        
class Derived extends Base {
    @Override
    protected void abstractMethod() {
        System.out.println("Derived implementation");
    }

    @Override
    public void interfaceMethod() {
        System.out.println("I still can change this");
    }
}

Having this layout, I want Base class to implement method from interface, but some of this implementation still depends on derived classes. I see no other way than make Base class not implement that interface and make derived to do so and reuse base class method in their implementation.

Is there any other way to protect derived classes from overriding interface method, which is implemented in Base class?


Solution

  • Just make it final:

        @Override
        public final void interfaceMethod() {
            baseClassMethod();
            abstractMethod();
        }
    

    So you cant override it again from your Derived class.