• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparator interface in java is a functional interface... why?  RSS feed

 
Ajit Kr Sharma
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The functional interface in java are those interfaces which has only one method to implement. Comparator interface in java 8 has 2 non default methods ie compare(T o1, T o2) and equals(Object obj). It is still called functional interface. Why?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The equals() method actually comes from class Object. 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).
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a definition of a functional interface in the Java® Language Specification (=JLS); it says specifically that methods inherited from Object do not count towards the definition of a functional interface.
Default methods are also excluded which means the Java8 version of Comparator has 18 methods and is still marked @FunctionalInterfaceEasier explanation to understand than in the JLS. It has one method from Object and 16 default methods, leaving only one fully abstract method.
 
Ajit Kr Sharma
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks @campbell, @Jesper for the detailed explanation.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Our pleasure
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!