Java Anonymous Classes
Classes without names for quick implementations
👤 What are Anonymous Classes?
Anonymous classes are classes without names that provide quick implementations of interfaces or abstract classes. They're perfect for one-time use and event handling scenarios.
// Anonymous class implementing interface
Runnable task = new Runnable() {
public void run() {
System.out.println("Task running...");
}
};
Types of Anonymous Classes
Interface Implementation
Implement interfaces on the fly
Clickable btn = new Clickable() {
public void click() { /* code */ }
};
Abstract Class Extension
Extend abstract classes inline
Animal dog = new Animal() {
void makeSound() { /* bark */ }
};
Event Handling
Perfect for GUI event listeners
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { }
});
Quick Implementation
No need for separate class files
// One-time use implementation
Comparator comp = new Comparator() {
public int compare(String a, String b) { }
};
🔹 Anonymous Class with Interface
Creating anonymous classes that implement interfaces:
// Interface definition
interface Greeting {
void sayHello(String name);
void sayGoodbye();
}
public class AnonymousExample {
public static void main(String[] args) {
// Anonymous class implementing Greeting interface
Greeting englishGreeting = new Greeting() {
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
public void sayGoodbye() {
System.out.println("Goodbye!");
}
};
// Another anonymous implementation
Greeting spanishGreeting = new Greeting() {
public void sayHello(String name) {
System.out.println("¡Hola, " + name + "!");
}
public void sayGoodbye() {
System.out.println("¡Adiós!");
}
};
// Using the anonymous classes
englishGreeting.sayHello("John");
englishGreeting.sayGoodbye();
spanishGreeting.sayHello("María");
spanishGreeting.sayGoodbye();
}
}
Output:
Hello, John! Goodbye! ¡Hola, María! ¡Adiós!
🔹 Anonymous Class with Abstract Class
Extending abstract classes using anonymous classes:
// Abstract class
abstract class Shape {
protected String color;
Shape(String color) {
this.color = color;
}
abstract double calculateArea();
void displayInfo() {
System.out.println("Shape color: " + color);
System.out.println("Area: " + calculateArea());
}
}
public class ShapeExample {
public static void main(String[] args) {
// Anonymous class extending Shape for Rectangle
Shape rectangle = new Shape("Red") {
private double length = 5;
private double width = 3;
double calculateArea() {
return length * width;
}
};
// Anonymous class extending Shape for Circle
Shape circle = new Shape("Blue") {
private double radius = 4;
double calculateArea() {
return 3.14159 * radius * radius;
}
};
// Using anonymous classes
System.out.println("Rectangle Info:");
rectangle.displayInfo();
System.out.println("\nCircle Info:");
circle.displayInfo();
}
}
Output:
Rectangle Info: Shape color: Red Area: 15.0 Circle Info: Shape color: Blue Area: 50.26536
🔹 Real-World Example: Event Handling
Anonymous classes are commonly used in GUI programming:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Anonymous Class Example");
JButton button1 = new JButton("Click Me!");
JButton button2 = new JButton("Press Me!");
// Anonymous class for button1 click event
button1.addActionListener(new ActionListener() {
private int clickCount = 0;
public void actionPerformed(ActionEvent e) {
clickCount++;
System.out.println("Button 1 clicked " + clickCount + " times!");
if (clickCount >= 3) {
JOptionPane.showMessageDialog(frame, "You clicked 3 times!");
}
}
});
// Another anonymous class for button2
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] options = {"Hello", "Hi", "Hey"};
String greeting = options[(int)(Math.random() * 3)];
JOptionPane.showMessageDialog(frame, greeting + " there!");
}
});
// Setup frame
frame.setLayout(new FlowLayout());
frame.add(button1);
frame.add(button2);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Behavior:
• Button 1 counts clicks and shows message after 3 clicks
• Button 2 shows random greeting messages
• Each button has its own anonymous ActionListener
🔹 Anonymous Classes vs Lambda Expressions
Java 8 introduced lambda expressions as a more concise alternative:
Anonymous Class vs Lambda:
- Anonymous Class: More verbose but supports multiple methods
- Lambda Expression: Concise but only for functional interfaces
- Performance: Lambdas are generally more efficient
- Scope: Different handling of 'this' keyword
import java.util.*;
public class ComparisonExample {
public static void main(String[] args) {
List names = Arrays.asList("John", "Alice", "Bob", "Charlie");
// Using Anonymous Class
Collections.sort(names, new Comparator() {
public int compare(String a, String b) {
return a.length() - b.length(); // Sort by length
}
});
System.out.println("Anonymous class result: " + names);
// Reset list
names = Arrays.asList("John", "Alice", "Bob", "Charlie");
// Using Lambda Expression (Java 8+)
Collections.sort(names, (a, b) -> a.length() - b.length());
System.out.println("Lambda expression result: " + names);
// Even more concise with method reference
names = Arrays.asList("John", "Alice", "Bob", "Charlie");
Collections.sort(names, Comparator.comparing(String::length));
System.out.println("Method reference result: " + names);
}
}
Output:
Anonymous class result: [Bob, John, Alice, Charlie] Lambda expression result: [Bob, John, Alice, Charlie] Method reference result: [Bob, John, Alice, Charlie]