请就以下问题给我建议。
我有 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 中运行)而不从 super 复制和粘贴现有代码吗?怎么办?
最佳答案
如果您想重用逻辑,则必须使用命名类实例而不是匿名类实例。
例如:
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
.......
}
});
}
}
关于java - 如何在方法内重写 Runnable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29408966/