Anonymous Classes as Functional Interface Implementations
What you'll learn: How anonymous classes can implement functional interfaces and why lambdas offer a cleaner alternative.
The Connection Between Anonymous Classes and Functional Interfaces
A functional interface is an interface with exactly one abstract method (like Comparator, Runnable, or custom interfaces you create). When you use an anonymous class to implement a functional interface, you're creating an entire class definition just to override that single method.
This works perfectly—you've already used anonymous classes for Comparator and Runnable in previous lessons—but there's a more concise way to do the same thing when dealing with functional interfaces specifically.
The Old Way vs The Modern Way
Consider this anonymous class implementing a functional interface:
Comparator<String> lengthComparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
};
Since Comparator has only one abstract method, this entire anonymous class can be replaced with a lambda expression (which you haven't learned yet, but will soon):
// Same functionality, much cleaner syntax
Comparator<String> lengthComparator = (s1, s2) -> s1.length() - s2.length();
Both approaches do exactly the same thing—they create an object that implements the functional interface.
When This Matters
Anytime you write an anonymous class that implements an interface with just one abstract method, you're creating a functional interface implementation. These are prime candidates for lambda conversion, which reduces boilerplate dramatically.
Key Takeaway: Anonymous classes that implement functional interfaces work perfectly but involve verbose syntax; recognizing this pattern prepares you for the more concise lambda syntax that serves the same purpose.