Junior
What are anonymous classes and where are they used?
sobes.tech AI
Answer from AI
An anonymous class is a local inner class without a name.
-
Used in:
- Creating event listeners in GUI applications (e.g., for buttons).
- Implementing interfaces or extending abstract classes "on the spot" when only one instance is needed and its use is local.
- In multithreading for creating instances of
RunnableorCallable.
-
Advantages:
- Reduces code volume when a separate class reuse is not required.
- Simplifies code reading for simple, one-time implementations.
-
Disadvantages:
- Can make code less readable for complex implementations.
- Cannot be reused.
- Access to outer class fields only through
finalor effectively final variables in older Java versions.
// Example of using an anonymous class for Runnable
Runnable myRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Running in an anonymous class thread.");
}
};
new Thread(myRunnable).start();
// Example of using an anonymous class for an event listener (hypothetical)
// Some UI frameworks use this approach.
//button.setOnAction(new EventHandler<ActionEvent>() {
// @Override
// public void handle(ActionEvent event) {
// System.out.println("Button clicked!");
// }
//});