Main Tutorials

Is Comparator a function interface, but it has two abstract methods?

Review the Comparator class; it has two abstract methods, why it can be a function interface?

Comparator.java

package java.util;

@FunctionalInterface
public interface Comparator<T> {

  // abstract method
  int compare(T o1, T o2);

  // abstract method
  boolean equals(Object obj);

  // few default and static methods
}

Definition of function interface
Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. 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.

Answer

Yes, Comparator is a functional interface. The equals is an abstract method overriding one of the public methods of java.lang.Object, this doesn’t count as an abstract method.


boolean equals(Object obj);

The Comparator only has one abstract method int compare(T o1, T o2), and it meet the definition of functional interface.

Comparator.java

package java.util;

@FunctionalInterface
public interface Comparator<T> {

  // abstract method
  int compare(T o1, T o2);

  // abstract method, overriding public methods of `java.lang.Object`
  // this doesn't count!
  boolean equals(Object obj);

  // few default and static methods
}

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Dovi
4 years ago

Really interesting!
Thank you!

rahul
2 years ago

Okkk, but how one interface implement any class like, Comparator extends Object?

Riley
3 years ago

Thank you, this was exactly the question i was looking for an answer to. Most explanations don’t qualify the definition of a functional interface with this important factor.

Vlakov
1 year ago

Thank you – very importnat