5

I would like to clarify my understanding of @FunctionalInterface a bit. As far as I know, we can add @FunctionalInterface annotation on an interface that only has one abstract method (It can have multiple default and static methods though.

In Java 8, Comparator<T> interface has been marked with @FunctionalInterface so it can be used in Lambda Expression but when I opened the definition, I could see 2 abstract class there

int compare(T o1, T o2); and boolean equals(Object obj);

I would like to understand how it is possible to have more than 2 abstract methods in the functional interface and still not getting any error? Help me to clear my understandings on this.

Ritam Das
  • 183
  • 1
  • 3
  • 12

2 Answers2

6

Your question is answered in the Java docs of the @FunctionalInterface annotation:

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.

So presence of the presence of boolean equals(Object obj); in the Comparator interface does not add to the count of abstract methods present in the interface and so we can apply @FunctionalInterface to this interface.

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
3

boolean equals(Object obj) is already defined on java.lang.Object so it is not really a "new" method in the interface. It is only "repeated" here because the implementation contract -- which is part of the Javadoc but not enforced by the compiler -- is being made stricter (it has to be consistent with compare).

Thilo
  • 257,207
  • 101
  • 511
  • 656