In Java...
I am creating a class Foo which contains a method doAction(). My requirements:
abstract would work, except that it does not allow me specify a function body for doAction().
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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With