How does the compiler recognize and verify the compliance of an interface marked as functional?
sobes.tech AI
Answer from AI
In Java, a functional interface is an interface with exactly one abstract method. The compiler recognizes such an interface by the number of abstract methods: if there is exactly one, the interface is considered functional.
The check occurs during compilation: if the interface is annotated with @FunctionalInterface, the compiler additionally verifies that there is indeed only one abstract method in the interface. If the annotation is absent, the interface is still considered functional if it has exactly one abstract method.
Example:
@FunctionalInterface
public interface MyFunction {
void apply(); // only abstract method
}
Attempting to add a second abstract method will result in a compilation error.
Thus, the compiler determines a functional interface based on the number of abstract methods and the @FunctionalInterface annotation, ensuring correct usage of lambda expressions and method references.