Skip to content
C

Functional Interfaces

A functional interface is an interface that contains exactly one abstract method. It's the type of interface that lambda expressions are designed to implement directly.


1. What is a Functional Interface?

A functional interface is an interface that contains exactly one abstract method. It's the type of interface that lambda expressions are designed to implement directly.

2. Why is it used?

Functional interfaces provide the foundation that makes lambda expressions possible — the lambda's short code becomes the implementation of that one single abstract method defined in the interface.

3. Real-Life Example

Think of a job role with exactly one single core responsibility, like "Deliver the package." Because there's only one clear task, anyone can quickly describe how they'll do it, without needing a long, detailed job description — that's the simplicity a functional interface provides.

4. Syntax

java
@FunctionalInterface interface InterfaceName { void methodName(); // exactly one abstract method }

5. Example Program

java
@FunctionalInterface interface Calculator { int operate(int a, int b); } public class FunctionalInterfaceDemo { public static void main(String[] args) { Calculator addition = (a, b) -> a + b; System.out.println("Sum: " + addition.operate(5, 10)); } }

Output:

Sum: 15

6. Key Points to Remember

  • The @FunctionalInterface annotation is optional, but it helps the compiler catch accidental extra methods.
  • Java provides many built-in functional interfaces in java.util.function, like Function, Predicate, and Consumer.
  • A functional interface can still have default and static methods, as long as there's exactly one abstract method.