Junior — Middle
Is it permissible to have two methods in a functional interface?
sobes.tech AI
Answer from AI
A functional interface in Java is an interface with exactly one abstract method. Having two or more abstract methods makes the interface non-functional.
However, an interface can contain multiple methods for the following reasons:
- Default methods — have an implementation and are not considered abstract.
- Static methods — are also not abstract.
Thus, it is permissible to have several methods in an interface, but only one of them should be abstract for the interface to be considered functional and usable, for example, with lambda expressions.
Example of a functional interface:
@FunctionalInterface
public interface MyFunction {
void apply(); // the only abstract method
default void log() {
System.out.println("Logging");
}
}
If a second abstract method is added, the compiler will generate an error.