Junior — Middle
Can you explain what a functional interface in Java is and why it is needed?
sobes.tech AI
Answer from AI
A functional interface in Java is an interface with exactly one abstract method. It is used to support functional programming and allows the use of lambda expressions and method references.
Why is this needed:
- Simplifies code by allowing the writing of concise anonymous functions.
- Improves readability and expressiveness.
- Enables passing behavior as a parameter.
Example of a functional interface:
@FunctionalInterface
public interface Calculator {
int calculate(int a, int b);
}
// Usage with a lambda expression
Calculator sum = (a, b) -> a + b;
int result = sum.calculate(5, 3); // result = 8
The @FunctionalInterface annotation is not mandatory but helps the compiler verify that the interface is indeed functional.