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?
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.
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.
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.
Use an Initializer Block:
new AbstractAction() {
{
// do stuff here
}
public void actionPerformed(ActionEvent event) {
...
}
}
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:
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) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With