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

author image

mkyong

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. Read all published posts by

Comments

avatar
newest oldest most voted
Dovi
Guest
Dovi

Really interesting!
Thank you!