Custom Functional Interfaces
Define your own with @FunctionalInterface.
What Makes an Interface Functional
A functional interface has exactly one abstract method (SAM). That single method is what a lambda implements.
- Default and static methods do not count against the limit.
interface Greeter {
String greet(String name);
}
public class Main {
public static void main(String[] args) {
Greeter g = name -> "Hello, " + name;
System.out.println(g.greet("Ada"));
}
}The @FunctionalInterface Annotation
@FunctionalInterface tells the compiler to enforce the single-abstract-method rule. If you accidentally add a second abstract method, compilation fails.
@FunctionalInterface
interface Calculator {
int compute(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
System.out.println(add.compute(3, 4));
}
}All lessons in this course
- Function and BiFunction
- Supplier and Consumer
- Predicate and Composition
- Custom Functional Interfaces