Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access outer anonymous class from inner anonymous class

I'm just curious. Is there a way to access parent in anonymous class that is inside another anonymous class?

I make this example create a JTable subclass (anonymous class) override changeSelection and inside i create another anonymous class.

MCVE:

public class Test{

    public static void main(String args []){

        JTable table = new JTable(){

            @Override
            public void changeSelection(
                final int row, final int column,
                final boolean toggle, final boolean extend) {

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        super.changeSelection(row, column, toggle, extend); 
                        //more code here
                    }
                });
            }
        };

    }//end main

}//end test 

How can i refer to super.changeSelection(..) ?

like image 436
nachokk Avatar asked Aug 05 '13 16:08

nachokk


People also ask

How do you refer to outer class from inner class?

If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.

Can inner classes access outer class private members?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Can inner class access outer class private methods Java?

Inner classes can even access the private variables/methods of outer classes.

Can inner class inherit outer class?

Inner class can extend it's outer class. But, it does not serve any meaning. Because, even the private members of outer class are available inside the inner class. Even though, When an inner class extends its outer class, only fields and methods are inherited but not inner class itself.


1 Answers

Unfortunately, you will have to give a name to the outer anonymous class:

public class Test{

    public static void main(String args []){

        class Foo extends JTable {

            @Override
            public void changeSelection(
                final int row, final int column,
                final boolean toggle, final boolean extend) {

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        Foo.super.changeSelection(row, column, toggle, extend); 
                        //more code here
                    }
                });
            }
        };

        JTable table = new Foo();

    }//end main

}//end test 
like image 83
newacct Avatar answered Oct 21 '22 00:10

newacct