问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/43616649/how-can-comparator-be-a-functional-interface-when-it-has-two-abstract-methods