A functional interface is the best choice when a piece of behavior needs to be passed as an argument rather than creating separate classes for every implementation. It is especially useful for callbacks, event handling, task execution, and custom business rules where only a single abstract method is required. Combined with lambda expressions, it makes the code concise, readable, and easy to maintain.
Key Points: • Functional interfaces work seamlessly with lambda expressions and method references introduced in Java 8. • They eliminate the need for creating multiple anonymous or concrete classes for simple behaviors. • Common examples include callbacks, event listeners, sorting logic, filtering operations, and asynchronous task execution.
Example: Consider an e-commerce application where different discount strategies must be applied to orders. Instead of creating multiple classes such as FestivalDiscount, PremiumCustomerDiscount, and CouponDiscount, a functional interface can be used to pass the discount logic dynamically.
Code Example:
@FunctionalInterface
interface DiscountStrategy {
double applyDiscount(double amount);
}
public class OrderService {
public static void main(String[] args) {
DiscountStrategy festivalDiscount =
amount -> amount * 0.90;
double finalAmount =
festivalDiscount.applyDiscount(1000);
System.out.println(
"Final Amount: "
+ finalAmount);
}
}Interview Tip: A concise interview answer is: A functional interface is ideal when a single piece of behavior needs to be passed dynamically. For example, in an e-commerce application, I can use a functional interface with lambda expressions to implement different discount strategies without creating multiple classes, resulting in cleaner, more flexible, and maintainable code.