Consider the following code:
for(int i = 0;i < 200;i++)
{
ArrayList<Integer> currentList = new ArrayList<Integer>() {{
add(i);
}};
// do something with currentList
}
currentList
? I'm just curious :)
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.
In Java, a class can contain another class known as nested class. It's possible to create a nested class without giving any name. A nested class that doesn't have any name is known as an anonymous class. Anonymous classes usually extend subclasses or implement interfaces.
3.12. An anonymous class cannot define any static fields, methods, or classes, except for staticfinal constants. Interfaces cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or static.
Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete). Interface.
ArrayList<Integer> currentList = new ArrayList<Integer>() {{
add(i);
}};
is creating a new instance of the anonymous class each time through your loop, it's not redefining or reloading the class every time. The class is defined once (at compile time), and loaded once (at runtime).
There is no significant performance hit from using anonymous classes.
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