覆盖由类层次结构中的另一个类最终确定的方法

时间:2018-10-19 04:12:44

标签: java inheritance

我遇到了这样的情况。

public class B{
    public final void run() {
    }
}

public class A extends B implements Runnable{
    //I want to implement Runnable's run method here.
    //But it does not allow as the run method in B is final
}

有人可以建议我实现这一目标的任何方法。

2 个答案:

答案 0 :(得分:3)

这里重要的是什么:AB还是ARunnable

如果是前者(或者同时是B Runnable很重要),您无能为力:B.run是最终决定,最后意味着您无法覆盖它。

如果是后者,请使用组合:

class A implements Runnable {
  final B b; // initialize on field or in constructor.

  @Override public void run() {
    // Your implementation, calling methods/fields on b
    // where you need the behaviour/data of B.
  }
}

答案 1 :(得分:1)

不幸的是,在给定的情况下,您无法在class A中实现run方法,就像在class B中声明了class A run方法的父类一样,您永远无法覆盖{{1} }方法。

您可以在final中更改方法的名称,也可以将方法设置为非最终形式。