I have an abstract class Task
with two methods execute()
and finish()
as the following:
abstract class Task {
abstract void execute();
private void finish() {
// Do something...
}
}
How can I ensure that the overloaded method execute()
in subclasses of Task
implicitly calls finish()
as the last statement?
You can create a ExecutorCloseable
class that implements the [AutoCloseable]
interface, such as:
public class ExecutorCloseable extends Foo implements AutoCloseable
{
@Override
public void execute()
{
// ...
}
@Override //this one comes from AutoCloseable
public void close() //<--will be called after execute is finished
{
super.finish();
}
}
You could call it this way (silly main()
example):
public static void main(String[] args)
{
try (ExecutorCloseable ec = new ExecutorCloseable ())
{
ec.execute();
} catch(Exception e){
//...
} finally {
//...
}
}
Hope it makes sense, I can't really know how you call these methods nor how you create the classes. But hey, it's a try : )
For this to work, the finish()
method on Foo
should be protected
or public
(first one recommended), though.