Anonymous classes to lambdas and method references
Replace single-method anonymous classes with concise lambdas and method references.
Code Comparison
✕ Anonymous class
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
save(event);
}
});
✓ Java 8+
button.addActionListener(this::save);
See a problem with this code? Let us know.
Why the modern way wins
Less boilerplate
Removes the class declaration and override ceremony.
Better readability
Keeps attention on the operation being performed.
Still type-safe
The compiler checks the target functional-interface signature.
Old Approach
Anonymous class
Modern Approach
Method reference
Since JDK
8
Difficulty
Beginner
JDK Support
Anonymous classes to lambdas and method references
Available
Available since JDK 8 (March 2014).
How it works
Functional interfaces can be implemented with lambdas or method references. This removes anonymous-class ceremony while preserving static typing and the same callback contract.
Related Documentation
Proof