Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Comparator be a Functional Interface when it has two abstract methods? [duplicate]

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?

like image 869
Arun Avatar asked Apr 25 '17 16:04

Arun


People also ask

Can we have 2 abstract methods in functional interface?

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit.

How can Comparator be functional interface?

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).

CAN interface have multiple abstract methods?

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.

Is Comparator and functional interface comparable?

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.


2 Answers

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 from java.lang.Object or elsewhere.

And since equals is one of those methods, the "abstract method count" of the interface is still 1.

like image 140
luk2302 Avatar answered Oct 14 '22 19:10

luk2302


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 from java.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.

like image 29
gyre Avatar answered Oct 14 '22 20:10

gyre