load 方法最后在 Java 中调用另一个方法

我有一个Task具有两种方法的抽象类execute(),finish()如下所示:


abstract class Task {

  abstract void execute();


  private void finish() {

    // Do something...

  }

}

如何确保execute()子类中的重载方法Task 隐式调用finish()为最后一条语句?


浮云间
浏览 84回答 2
2回答

qq_遁去的一_1

我不相信有任何方法可以“强制”子类调用方法,但您可以尝试某种模板方法方法:abstract class Foo {&nbsp; protected abstract void bar();&nbsp; &nbsp; &nbsp;// <--- Note protected so only visible to this and sub-classes&nbsp; private void qux() {&nbsp; &nbsp; // Do something...&nbsp; }&nbsp; // This is the `public` template API, you might want this to be final&nbsp; public final void method() {&nbsp; &nbsp; bar();&nbsp; &nbsp; qux();&nbsp; }}publicmethod是入口点,调用抽象方法bar然后调用私有qux方法,这意味着任何子类都遵循模板模式。然而,这当然不是灵丹妙药——一个子类可以简单地忽略 public method。

湖上湖

您可以创建一个ExecutorCloseable实现该[AutoCloseable]接口的类,例如:public class ExecutorCloseable extends Foo implements AutoCloseable&nbsp;{&nbsp; @Override&nbsp; public void execute()&nbsp;&nbsp; {&nbsp; &nbsp; // ...&nbsp; }&nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//this one comes from AutoCloseable&nbsp; public void close() //<--will be called after execute is finished&nbsp; {&nbsp; &nbsp; &nbsp;super.finish();&nbsp; }&nbsp;}你可以这样称呼它(愚蠢的main()例子):&nbsp;public static void main(String[] args)&nbsp;&nbsp;{&nbsp; &nbsp; &nbsp;try (ExecutorCloseable ec = new ExecutorCloseable ())&nbsp;&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; ec.execute();&nbsp; &nbsp; &nbsp;} catch(Exception e){&nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; &nbsp;} finally {&nbsp; &nbsp; &nbsp; &nbsp;//...&nbsp; &nbsp; }&nbsp;}希望它有意义,我真的不知道你如何调用这些方法,也不知道你如何创建类。但是,嘿,这是一个尝试:)不过,要使其起作用,finish()方法Foo应该是protectedor public(推荐第一个)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java