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

Using @FunctionalInterface with Custom Interfaces

Practice annotating your own functional interfaces and see how it improves code clarity and intent for lambda users.

Using @FunctionalInterface with Custom Interfaces

You'll learn how applying @FunctionalInterface to your own interfaces improves code clarity and helps lambda users understand your API's intent.

Why Annotate Your Custom Interfaces

When you design an interface meant to be implemented with lambdas, adding @FunctionalInterface tells both the compiler and other developers: "This interface has exactly one abstract method and is designed for functional programming." It's like putting a sign on a door that says "Single Entrance Only" — you're declaring your interface's purpose explicitly.

How It Works in Practice

Imagine you're creating a custom callback interface for data processing:

@FunctionalInterface
public interface DataProcessor {
    String process(String input);
}

Now users immediately know they can write clean lambda expressions:

DataProcessor uppercase = s -> s.toUpperCase();
DataProcessor addPrefix = s -> "Processed: " + s;

Without @FunctionalInterface, developers might wonder: "Can I use a lambda here? Is this interface stable?" The annotation answers these questions definitively.

Protection Against Accidental Changes

The real power comes when you (or a teammate) later try to add a second abstract method:

@FunctionalInterface
public interface DataProcessor {
    String process(String input);
    void validate(String input);  // Compiler error!
}

Boom! The compiler stops you immediately, preventing a breaking change that would invalidate all existing lambda usage.

Clarity for API Users

When someone reads your code and sees @FunctionalInterface, they instantly understand your design intent. It's documentation that's enforced by the compiler — the best kind.

Key Takeaway: Always annotate your custom single-method interfaces with @FunctionalInterface to signal lambda compatibility, prevent accidental API breakage, and make your code's intent crystal clear to other developers.