Java Notes
Learn anonymous classes in Java — one-time implementation of an interface or abstract class without naming the class, when to use them, and how lambdas replaced many anonymous classes.
An anonymous class is a class that is defined and instantiated at the same time, with no name. You use it when you need a one-time implementation of an interface or abstract class, and creating a separate named class would be overkill.
The Problem It Solves
Suppose you have an interface Greeting and you want to use it just once, in one specific place:
Without anonymous class — you must create a named class:
public interface Greeting {
void greet();
}
// Separate file or inner class just for this one use
public class FormalGreeting implements Greeting {
@Override
public void greet() {
System.out.println("Good morning, sir.");
}
}
// Usage
Greeting g = new FormalGreeting();
g.greet();With anonymous class — define and use in one place:
Greeting g = new Greeting() {
@Override
public void greet() {
System.out.println("Good morning, sir.");
}
};
g.greet();No separate class file. No name. Declared inline, used immediately.
Full Runnable Example
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
new Animal() { ... }— creates an anonymous class that implementsAnimal. The{}block contains the method bodies.- No class name anywhere — it has an internal name assigned by the compiler (like
AnonymousDemo$1) but you never see it. fishandbirdboth implementAnimaldifferently, each defined inline.
Anonymous Class Extending an Abstract Class
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
new Shape("Blue") { ... }— creates an anonymous class extendingShape. The"Blue"in the parentheses goes to Shape's constructor.baseandheightare extra fields added in the anonymous class.area()is the required override.
Common Use: Comparator
Before Java 8, anonymous classes were the standard way to write comparators for sorting:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The Comparator is used once for this sort — no reason to create a named class. The anonymous class is inline and self-contained.
Anonymous Class vs Lambda
Java 8 introduced lambda expressions. For functional interfaces (interfaces with exactly one method), a lambda is shorter:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Lambda replaces anonymous class when the interface has exactly one abstract method. When an interface has multiple methods, you still need an anonymous class (or a named class).
What Anonymous Class Can and Cannot Do
Can:
- Implement an interface
- Extend a class (abstract or concrete)
- Have extra fields and methods
- Access outer class fields and
finallocal variables
Cannot:
- Have a constructor (it has no name to call)
- Be reused — each
new Interface() { }creates a fresh one-use class
Common Mistake: Thinking Anonymous Class Creates a New Object Each Time
This creates three separate anonymous class instances. The class definition is also essentially "new" each time (though Java reuses the class file). For heavy loops, prefer a named class or lambda.
Practice Task
Task: Create an interface Validator with one method boolean isValid(String input). In main, create two anonymous classes implementing Validator:
emailValidator— returns true if input contains "@"phoneValidator— returns true if input has exactly 10 characters and all are digits
Test both with a few inputs and print the results.
Hint: Use input.contains("@") for email. For phone, use input.length() == 10 and loop through Character.isDigit(input.charAt(i)).
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: Two different anonymous classes, both implementing the same interface. Each has completely different logic. Try rewriting emailValidator as a lambda: Validator emailValidator = input -> input != null && input.contains("@"); — same result, four lines become one.
Continue the lesson path