Junior — Middle
Is it possible to create methods for accepting and returning values in functional interfaces?
sobes.tech AI
Answer from AI
In a functional interface in Java, there must be exactly one abstract method (SAM — Single Abstract Method). This method defines the signature for accepting and returning values.
You can create additional methods, but:
- They must be either default (with implementation),
- Or static,
- Or methods from
java.lang.Object(e.g.,equals,hashCode,toString).
There should be no abstract methods other than the one.
Example:
@FunctionalInterface
public interface MyFunction {
int apply(int x); // main abstract method
default int doubleApply(int x) { // additional method with implementation
return apply(x) * 2;
}
static int staticMethod() { // static method
return 42;
}
}
Thus, the method for accepting and returning values is the only abstract method of the interface. Other methods with implementation can be created, but they do not affect the interface's functionality.