How can a Comparator be a functional interface when it has two abstract methods?

Java 8 introduces the @FunctionalInterface annotation to denote any interface that has exactly one abstract method as a functional interface. One of the reasons for introducing it is to tell the user (programmer) that the lambda expression can be used in the context of a functional interface.

The Comparator interface is annotated using @FunctionalInterface . But two methods are abstract.

 int compare(T o1, T o2); 

and

 boolean equals(Object obj); 

In FunctionalInterface docs, it is explicitly referred to as

A conceptually functional interface has exactly one abstract method.

Isn't the equals method considered abstract here?

+5
source share
2 answers

The documents also indicate:

If the interface declares an abstract method overriding one of the public java.lang.Object methods, this also does not take into account the abstract method of the interface, since any interface implementation will have an implementation from java.lang.Object or elsewhere.

And since equals is one of these methods, the "abstraction method counter" of the interface remains 1.

+14
source

Also from the FunctionalInterface documentation page :

If the interface declares an abstract method , overriding one of the public methods java.lang.Object , this also does not take into account the abstract method of the interface, since any implementation of the interface will have an implementation from java.lang.Object or elsewhere. [emphasis mine]

Since equals is a public Object method, this statement applies; thus, for Comparator only the compare method contributes to the calculation of the abstract method.

Other known methods to which this rule applies are toString and hashCode .

+8
source

Source: https://habr.com/ru/post/1267150/


All Articles