I am trying to learn more about the Java 8 FunctionalInterface
annotation. I wrote the following code as an experiment, but it does not compile:
@FunctionalInterface
public interface HasToString {
String toString();
}
No target method found
Interestingly, this does compile:
@FunctionalInterface
public interface HasToString {
String notToString();
}
Why is this?
An Interface that contains exactly one abstract method is known as functional interface. It can have any number of default, static methods but can contain only one abstract method. It can also declare methods of object class. Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces.
stream. Stream is not a functional interface–it has numerous abstract methods.
A functional interface must have exactly one abstract method. A functional interface has any number of default methods because they are not abstract and implementation already provided by the same.
The functional interface also known as Single Abstract Method Interface was introduced to facilitate Lambda functions. Since a lambda function can only provide the implementation for 1 method it is mandatory for the functional interface to have ONLY one abstract method.
This is stated in the JLS 9.8
A functional interface is an interface that has just one abstract method (aside from the methods of Object), and thus represents a single function contract. This "single" method may take the form of multiple abstract methods with override-equivalent signatures inherited from superinterfaces; in this case, the inherited methods logically represent a single method.
As toString
is a "public instance method of the class Object", your interface doesn't qualify to be a functional interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With