A Functional Interface in Java 8 is an interface that has exactly one abstract method (SAM – Single Abstract Method). It can have any number of default and static methods, but only one abstract method.
Functional interfaces are the foundation of Lambda Expressions and Method References in Java 8.
✅ Key Points
- Only one abstract method → defines the functional behavior.
- Can have multiple default or static methods.
- Can be annotated with
@FunctionalInterface
(optional, but useful for compiler checks). - Used heavily in Java 8’s Streams API and functional programming features.
✅ Example of a Functional Interface
@FunctionalInterface
interface MyFunctionalInterface {
void sayMessage(String msg); // Single Abstract Method (SAM)
// Default method
default void printHello() {
System.out.println("Hello from default method!");
}
// Static method
static void printStatic() {
System.out.println("Hello from static method!");
}
}
✅ Usage with Lambda Expression
public class FunctionalInterfaceDemo {
public static void main(String[] args) {
// Using lambda expression
MyFunctionalInterface message = (msg) -> {
System.out.println("Message: " + msg);
};
message.sayMessage("Java 8 is powerful!");
message.printHello(); // default method
MyFunctionalInterface.printStatic(); // static method
}
}
✅ Built-in Functional Interfaces in Java 8
Java provides many pre-defined functional interfaces in the java.util.function
package, such as:
- Predicate →
boolean test(T t)
- Function<T, R> →
R apply(T t)
- Consumer →
void accept(T t)
- Supplier →
T get()
- UnaryOperator →
T apply(T t)
- BinaryOperator →
T apply(T t1, T t2)