Junior — Middle
Can an interface containing only one method be considered a functional interface according to Java standards?
sobes.tech AI
Answer from AI
Yes, in Java, an interface that contains exactly one abstract method is considered a functional interface. This definition is established in the Java 8 specification and above. Such an interface can be used in lambda expressions and method references.
To explicitly indicate that an interface is a functional interface, the @FunctionalInterface annotation is used, although it is not mandatory, but it helps the compiler verify compliance.
Example:
@FunctionalInterface
public interface MyFunction {
void execute();
}
// Usage with a lambda expression
MyFunction func = () -> System.out.println("Hello");
func.execute();