What is a Functional Interface in Java?
Definition
A functional interface in Java must have exactly one abstract method and may have other default or static methods.
Example
@FunctionalInterface
public interface Calculator {
int add(int a, int b);
default void log(String message) {
System.out.println("Log: " + message);
}
static void showResult(int result) {
System.out.println("Result: " + result);
}
}
// Using Lambda
Calculator calculator = (a, b) -> a + b;
int result = calculator.add(5, 3);
Calculator.showResult(result);
A default
method in an interface offers a built-in implementation that can be replaced by any class using it. This feature is exclusive to interfaces.
Commentaires
Enregistrer un commentaire