Course contentsShow
← Java
Lesson 2415 of 2,87046. AnnotationsFree lesson

@FunctionalInterface: Marking Single Abstract Method Interfaces

Learn what @FunctionalInterface does and how it enforces that an interface has exactly one abstract method for lambda compatibility.

@FunctionalInterface: Marking Single Abstract Method Interfaces

What you'll learn: How @FunctionalInterface enforces that an interface contains exactly one abstract method, making it safe for lambda expressions.

What Is @FunctionalInterface?

@FunctionalInterface is a compiler annotation that marks an interface as a functional interface—meaning it must have exactly one abstract method (SAM: Single Abstract Method). This annotation acts as a contract enforcer: if someone accidentally adds a second abstract method to the interface, the compiler immediately flags an error.

Why It Matters for Lambda Compatibility

Lambda expressions in Java work only with functional interfaces. When you write a lambda, you're actually implementing that single abstract method. Without @FunctionalInterface, you might unknowingly add a second abstract method to an interface, breaking all existing lambda code that uses it. This annotation prevents that mistake.

Think of it like a "single-door room" label—it guarantees there's exactly one entrance, so everyone knows which door to use. Lambda expressions need that certainty.

How It Works

@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);  // Single abstract method
    // Adding another abstract method here causes a compiler error
}

// Lambda implementation now guaranteed to work
Calculator add = (a, b) -> a + b;

The interface can still have default methods, static methods, or methods inherited from Object (like toString())—those don't count toward the SAM requirement. Only abstract methods matter.

When to Use It

Apply @FunctionalInterface whenever you design an interface specifically for lambda usage. It's optional—interfaces with one abstract method work with lambdas anyway—but it documents your intent and protects against future mistakes.

Key Takeaway: @FunctionalInterface is a safety annotation that tells the compiler to verify an interface has exactly one abstract method, preventing accidental breakage of lambda-compatible interfaces.