Let's say I have an interface with some methods, like this:
interface Task {
void before();
void doStuff();
void after();
}
Here I would implement part of it:
abstract class PoliteTask implements Task{
@Override
public void before() {
System.out.println("Hey");
}
@Override
public abstract void doStuff();
@Override
public void after() {
System.out.println("Cya");
}
}
Now I want to make sure that those before()
and after()
implementations are called in all extending classes.
Here we have a class that needs to init something in before()
:
class ActualStuffTask extends PoliteTask {
private int fancyNumber;
@Override
public void before() {
// init some things
fancyNumber = 42;
}
@Override
public void doStuff() {
System.out.println("Look, a number: "+fancyNumber);
}
}
Obviously, ActualStuffTask
overrides before()
, hence it does not say "Hey", only "Cya".
If I made the methods in PoliteTask
final
, this wouldn't happen, but then it's child classes could not override the methods.
Calling super.before()
in the ActualStuffTask
would work, but I want to have this effect guaranteed, regardless of child class implementation.
The question is:
What pattern should I use to have both parent implementation, and child implementation?