A functional interface is an interface that contains exactly one abstract method. It serves as the foundation for lambda expressions, method references, and functional programming features introduced in Java 8. Although it can contain multiple default and static methods, it must have only one abstract method.
Key Points: • A functional interface contains exactly one abstract method. • It enables the use of lambda expressions and method references. • The @FunctionalInterface annotation is optional but recommended. • Functional interfaces can include default and static methods. • Common examples include Runnable, Comparator, Callable, and Consumer.
Example: Suppose an application needs a simple operation to greet a user. A functional interface can define a single abstract method, and its implementation can be provided using a lambda expression.
Code Example:
@FunctionalInterface
interface Greeting {
void sayHello(String name);
}
public class Demo {
public static void main(String[] args) {Greeting greeting = name ->
System.out.println("Hello, " + name);
greeting.sayHello("Amol");
}
}Output:
Hello, Amol
Valid Functional Interface:
@FunctionalInterface
interface Calculator {
int add(int a, int b);
default void display() {
System.out.println("Calculator");
}
static void info() {
System.out.println("Utility Method");
}
}This is valid because there is only one abstract method.
Invalid Functional Interface:
@FunctionalInterface
interface Calculator {
int add(int a, int b);
int subtract(int a, int b);
}This is invalid because it contains two abstract methods.
Common Built-in Functional Interfaces:
• Runnable → void run() • Comparator<T> → int compare(T o1, T o2) • Consumer<T> → void accept(T t) • Supplier<T> → T get() • Predicate<T> → boolean test(T t) • Function<T,R> → R apply(T t)
Benefits of Functional Interfaces:
• Simplifies code using lambda expressions • Reduces boilerplate code • Improves readability • Supports functional programming concepts • Makes APIs more concise and expressive
Interview Tip: A concise interview answer is:
"A functional interface is an interface that contains exactly one abstract method. It is primarily used with lambda expressions and method references. Even though it can have multiple default and static methods, it must have only one abstract method to qualify as a functional interface."