Functional interface (FI) là interface có đúng một abstract method — tên chính thức SAM (Single Abstract Method).
Default/static method không tính.
@FunctionalInterface
interface Greeter {
void greet(String name); // 1 abstract method
default void greetAll(List<String> names) { names.forEach(this::greet); }
}@FunctionalInterface là annotation kiểm tra — compiler báo lỗi nếu thêm abstract method thứ 2.
Lambda — cú pháp implement FI gọn gàng:
Runnable r = () -> System.out.println("hi"); // Java 8+
Consumer<String> print = System.out::println; // method referenceFI hay gặp (java.util.function): Function<T,R>, Predicate<T>, Consumer<T>, Supplier<T>, BiFunction<T,U,R>.
FI có trước Java 8 vẫn dùng được với lambda: Runnable, Callable, Comparator.
Lambda vs anonymous class:
- Lambda không tạo class file mới — dùng invokedynamic, nhẹ hơn.
- this trong lambda = enclosing instance; trong anonymous class = chính object anonymous.
- Lambda chỉ capture biến effectively final.
A functional interface (FI) has exactly one abstract method — formally SAM (Single Abstract Method).
Default/static methods do not count.
@FunctionalInterface
interface Greeter {
void greet(String name); // 1 abstract method
default void greetAll(List<String> names) { names.forEach(this::greet); }
}@FunctionalInterface is a verification annotation — the compiler errors if a second abstract method is added.
Lambdas — concise FI implementations:
Runnable r = () -> System.out.println("hi"); // Java 8+
Consumer<String> print = System.out::println; // method referenceCommon FIs (java.util.function): Function<T,R>, Predicate<T>, Consumer<T>, Supplier<T>, BiFunction<T,U,R>.
Pre-Java 8 FIs still work with lambdas: Runnable, Callable, Comparator.
Lambda vs anonymous class:
- Lambdas do not produce a new class file — they use invokedynamic, lighter.
- this in a lambda = enclosing instance; in an anonymous class = the anonymous object itself.
- Lambdas can only capture effectively final locals.