Junior — Middle
How to define a single abstract method in an interface that corresponds to a functional interface in Java?
sobes.tech AI
Answer from AI
In Java, a functional interface is an interface that contains exactly one abstract method (SAM — Single Abstract Method). To define such a method, you need to ensure that there is only one method without an implementation in the interface.
Example:
@FunctionalInterface
public interface MyFunctionalInterface {
void execute(); // single abstract method
// You can add methods with default implementation
default void log() {
System.out.println("Logging...");
}
}
The @FunctionalInterface annotation is not mandatory but recommended, as the compiler will check that the interface is indeed functional.
Thus, the single abstract method is a method without a body that defines the contract of the interface, and all other methods are either absent, have a default implementation, or are static.