2 回答

TA貢獻1725條經驗 獲得超8個贊
我不相信有任何方法可以“強制”子類調用方法,但您可以嘗試某種模板方法方法:
abstract class Foo {
protected abstract void bar(); // <--- Note protected so only visible to this and sub-classes
private void qux() {
// Do something...
}
// This is the `public` template API, you might want this to be final
public final void method() {
bar();
qux();
}
}
publicmethod是入口點,調用抽象方法bar然后調用私有qux方法,這意味著任何子類都遵循模板模式。然而,這當然不是靈丹妙藥——一個子類可以簡單地忽略 public method。

TA貢獻2003條經驗 獲得超2個贊
您可以創建一個ExecutorCloseable
實現該[AutoCloseable]
接口的類,例如:
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();
}
}
你可以這樣稱呼它(愚蠢的main()例子):
public static void main(String[] args)
{
try (ExecutorCloseable ec = new ExecutorCloseable ())
{
ec.execute();
} catch(Exception e){
//...
} finally {
//...
}
}
希望它有意義,我真的不知道你如何調用這些方法,也不知道你如何創建類。但是,嘿,這是一個嘗試:)
不過,要使其起作用,finish()方法Foo應該是protectedor public(推薦第一個)。
添加回答
舉報