我遇到了这样的情况。
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
}
有人可以建议我实现这一目标的任何方法。
答案 0 :(得分:3)
这里重要的是什么:A
是B
还是A
是Runnable
?
如果是前者(或者同时是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
中更改方法的名称,也可以将方法设置为非最终形式。