Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a method implementation in base class which requires override in subclasses?

In Java...

I am creating a class Foo which contains a method doAction(). My requirements:

  1. doAction() must have a default implementation (i.e. function body) in Foo.
  2. All subclasses of Foo must override doAction(), meaning that subclasses will get a compiler error if they do not provide a new implementation.
  3. I need to be able to instantiate Foo.

abstract would work, except that it does not allow me specify a function body for doAction().

like image 252
frankadelic Avatar asked Feb 23 '23 10:02

frankadelic


2 Answers

Edit

It is impossible to simultaneously satisfy all of the requirements, end of story. You must give up at least one condition, and probably consider an entirely different approach to the problem you're trying to solve.


Use two separate methods. Either:

abstract class Foo {
    
    // Override this method
    abstract void doActionInSubclass();
    
    // You can't override a final method
    // And you don't want subclases to override this one
    final void doAction () {
        // do whatever default-y things you want here
        doActionInSubclass();
    }
}

Or just make the "required" method completely separate from the one you want to force subclasses to override:

abstract class Foo {
    abstract void mustOverrideThisInConcreteSubclasses();
    
    final void doAction() {
        // default-y things here
    }
}
like image 73
Matt Ball Avatar answered Feb 25 '23 00:02

Matt Ball


If you give a default implementation to a method in Java, you can't force the subclasses to override it again. If you can, use a template method pattern using a different method name:

public class Foo{

    public abstract void templateMethod();
    public final void doAction(){

    //default implementation

     templateMethod(); // call template method
    }
}
like image 27
Heisenbug Avatar answered Feb 24 '23 23:02

Heisenbug