Search code examples
javaoverridingactionlistenerextend

How to override Runnable inside a method?


Please, give me an advice for following question.

I have class A & class B How to override Runnable inside a method foo in class B?

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
                .......
            }
        });
    }

}

Can I add new code to button's handler (Runnable in myButton) without copying&pasting existing code from super? How?


Solution

  • You would have to use named class instances instead of anonymous class instances if you want to re-use the logic.

    For example :

    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());
                .......
        }
    }
    

    Then B can override that logic :

    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
                    .......
                }
            });
    
    
        }
    
    }