What is Functional Interface in Java: Definition and Example
functional interface in Java is an interface that has exactly one abstract method. It is used to represent a single action or behavior, often enabling lambda expressions and method references for concise code.How It Works
A functional interface in Java acts like a contract with only one main task to perform, similar to a single-button remote control that does one specific thing. This simplicity allows Java to treat it as a target for lambda expressions, which are short blocks of code that can be passed around and executed later.
Think of it like a recipe card with just one recipe: you know exactly what to do without confusion. Java enforces this by allowing only one abstract method in the interface, but it can have multiple default or static methods that provide extra features without changing the main task.
Example
This example shows a functional interface named Greeting with one abstract method sayHello. We use a lambda expression to provide the method's behavior, which prints a greeting message.
interface Greeting { void sayHello(String name); } public class Main { public static void main(String[] args) { Greeting greeting = name -> System.out.println("Hello, " + name + "!"); greeting.sayHello("Alice"); } }
When to Use
Use functional interfaces when you want to pass a simple behavior or action as a parameter, especially in situations like event handling, callbacks, or processing collections. They make your code cleaner and easier to read by replacing bulky anonymous classes with concise lambda expressions.
For example, in GUI programming, you might use a functional interface to define what happens when a button is clicked. In streams or collections, they help define operations like filtering or mapping data.
Key Points
- A functional interface has exactly one abstract method.
- It enables lambda expressions and method references.
- Can have default and static methods besides the single abstract method.
- Marked optionally with
@FunctionalInterfaceannotation for clarity and compile-time checking. - Commonly used in Java's built-in interfaces like
Runnable,Callable, andComparator.