java - 如何在方法内重写 Runnable?

标签 java overriding actionlistener extend

请就以下问题给我建议。

我有 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/

相关文章:

java - 我如何向 :action form 添加数据

java.lang.NullPointerException : Cannot get property 'text' on null object

java - 检查具有属性值的节点是否存在

html - 如何覆盖设置文件基础

c++ - 有没有办法隐藏已经在父级中声明的 Embarcadero __property?

java - 实例变量的值在两个类中是不同的。为什么? (+更多问题)

java - 使用 Runtime.getRuntime().exec(command) 启动程序时遇到问题

java - 如何为特定的 Jenkins 工作设置 `killSoftly`?

java - 是否可以说每个运行时绑定(bind)都是编译期间的静态绑定(bind)?

java - 一个事件有两个监听器?