In Java 8, the @FunctionalInterface
annotation is introduced to denote any interface that has exactly one abstract method as a functional interface. One of the reason for its introduction is to indicate the user (programmer), that lambda expression can be used in context of a functional interface.
The Comparator
interface is annotated with @FunctionalInterface
. But, two methods are abstract.
int compare(T o1, T o2);
and
boolean equals(Object obj);
In the docs of FunctionalInterface
, it is clearly mentioned as
Conceptually, a functional interface has exactly one abstract method.
Isn't the equals
method not considered as abstract here?
A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit.
All objects in Java already have an implementation of the equals() method, because they inherit it from class Object. So, Comparator is a functional interface because there's only one unimplemented abstract method: compare(T o1, T o2).
So we can have methods that can have their own body inside the interface one of them being static methods. So from Java 8 onwards it's not 100 % correct to say that interface can only have abstract methods.
We said that Comparator is a functional interface because it has a single abstract method. Comparable is also a functional interface since it also has a single abstract method.
The docs also state:
If an interface declares an abstract method overriding one of the public methods of
java.lang.Object
, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation fromjava.lang.Object
or elsewhere.
And since equals
is one of those methods, the "abstract method count" of the interface is still 1.
Also from the FunctionalInterface
documentation page:
If an interface declares an abstract method overriding one of the public methods of
java.lang.Object
, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation fromjava.lang.Object
or elsewhere. [emphasis mine]
Since equals
is a public method of Object
, this statement applies; thus, for Comparator
only the compare
method contributes to the abstract method count.
Other notable methods to which this rule applies are toString
and hashCode
.
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