@FunctionalInterface in Java: Definition and Usage Explained
@FunctionalInterface is an annotation used to mark an interface as a functional interface, which means it has exactly one abstract method. This annotation helps the compiler enforce the rule and improves code clarity when using lambda expressions or method references.How It Works
The @FunctionalInterface annotation tells Java that an interface is intended to have only one abstract method. Think of it like a contract that says, "This interface is a simple task with one job." The compiler checks this and gives an error if you add more than one abstract method.
This is useful because Java allows you to use lambda expressions or method references to create instances of these interfaces easily. It's like having a single button to press for a specific action, making your code cleaner and easier to read.
Example
This example shows a functional interface with one abstract method, and how a lambda expression implements it.
import java.util.function.Function; @FunctionalInterface interface Greeting { void sayHello(String name); } public class Main { public static void main(String[] args) { Greeting greet = (name) -> System.out.println("Hello, " + name + "!"); greet.sayHello("Alice"); } }
When to Use
Use @FunctionalInterface when you want to create an interface that represents a single action or behavior, especially if you plan to use lambda expressions or method references. It helps catch mistakes early by ensuring only one abstract method exists.
Common real-world uses include defining callbacks, event handlers, or simple operations like transforming data. For example, Java's built-in interfaces like Runnable or Comparator are functional interfaces.
Key Points
- @FunctionalInterface marks an interface with exactly one abstract method.
- It enables use of lambda expressions and method references for cleaner code.
- The compiler enforces the single abstract method rule when this annotation is present.
- It improves code readability and intent clarity.
- It is optional but recommended for functional interfaces.
Key Takeaways
@FunctionalInterface ensures an interface has only one abstract method.