请给我一个关于以下问题的建议。
我有A级和A级B级 如何在B类的方法foo中覆盖Runnable?
class A {
//some code
.......
protected void foo() {
//some code
.......
//adding click listener to instance of MyButton
myButton.show(new Runnable(){
@Override
public void run() {
.......
}
});
//some code
.......
}
//some code
.......
}
class B extends A {
@Override
protected void foo() {
super.foo();
//some NEW code
.......
//adding click listener to instance of MyButton
myButton.show(new Runnable(){
@Override
public void run() {
//Copied&Pasted old code
.......
//NEW code
.......
}
});
}
}
我可以向按钮的处理程序(myButton中的Runnable)添加新代码,而无需复制和粘贴来自super的现有代码吗?怎么样?
答案 0 :(得分:2)
如果要重新使用逻辑,则必须使用命名类实例而不是匿名类实例。
例如:
class A {
...
static class ButtonLogic implements Runnable
{
public void run() {...}
}
protected void foo() {
//adding click listener to instance of MyButton
myButton.show(new A.ButtonLogic());
.......
}
}
然后B可以覆盖该逻辑:
class B extends A {
@Override
protected void foo() {
super.foo();
//some NEW code
.......
//adding click listener to instance of MyButton
myButton.show(new A.ButtonLogic(){
@Override
public void run() {
super.run();
.......
//NEW code
.......
}
});
}
}