When @FunctionalInterface is Optional
You'll learn: The @FunctionalInterface annotation is purely documentary—any interface with exactly one abstract method works as a functional interface, annotation or not.
The Annotation Is a Courtesy, Not a Requirement
When you learned about @FunctionalInterface, you saw how it tells the compiler "verify this interface has exactly one abstract method." But here's the key insight: Java doesn't need the annotation to recognize a functional interface.
Any interface that happens to have a single abstract method (SAM) automatically qualifies as a functional interface. You can use it with lambda expressions, method references, and anywhere a functional interface is expected—whether or not you wrote @FunctionalInterface above it.
// No annotation, still a functional interface
interface Calculator {
int compute(int a, int b);
}
public class Demo {
public static void main(String[] args) {
// Works perfectly with lambdas
Calculator add = (x, y) -> x + y;
System.out.println(add.compute(5, 3)); // 8
Calculator multiply = (x, y) -> x * y;
System.out.println(multiply.compute(5, 3)); // 15
}
}
Why Use It Then?
The annotation serves two purposes: it documents your intent (this interface is designed to be used functionally), and it prevents accidents (the compiler will reject changes that break the SAM contract). But technically? Optional.
Think of @FunctionalInterface like a "Fragile" sticker on a box—the box doesn't need the sticker to be fragile, but the sticker prevents people from treating it roughly.
Key Takeaway: Any single-abstract-method interface is usable as a functional interface regardless of @FunctionalInterface; the annotation only adds compile-time verification and clarity.