Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize anonymous inner class in Java

Tags:

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?

like image 541
Jarek Avatar asked Mar 15 '11 10:03

Jarek


People also ask

How do you initialize an anonymous class in Java?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.

Can anonymous inner class be instantiated?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

How do you initialize an inner class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.


2 Answers

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:

like image 99
Sean Patrick Floyd Avatar answered Sep 22 '22 16:09

Sean Patrick Floyd


It's not quite clear what you mean, but you can use an initializer block to execute code at construction time:

new AbstractAction() {

    {
        // This code is called on construction
    }

    @Override public void actionPerformed(ActionEvent event) {
    ...
    }
}
like image 29
Jon Skeet Avatar answered Sep 22 '22 16:09

Jon Skeet