Jarek Jarek - 11 days ago 8
Java Question

How to initialize anonymous inner class in Java

Is there any way to initialize anonymous inner class in Java?

For example:

new AbstractAction() {
actionPerformed(ActionEvent event) {
...
}
}


Is there any way to use for example putValue method somewhere in the class declaration?

Answer

Use an Initializer Block:

new AbstractAction() {

    {
        // do stuff here
    }

    public void actionPerformed(ActionEvent event) {
    ...
    }
}

Initializing Instance Members

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

{
    // whatever code is needed for initialization goes here
}

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Source:

Comments