Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why @FunctionalInterface annotation is added to Comparator interface in Java 8?

Tags:

java

java-8

I understand that a bunch of methods with body are added using default keyword of Java 8. My question is where is this annotation useful? I see that only one abstract method is allowed to be added with such annotation. But Comparator has two abstract methods :

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

Also , Please explain the use of this annotation? I see that its a runtime annotation, so what are its uses ?

like image 666
javaAndBeyond Avatar asked Feb 08 '23 00:02

javaAndBeyond


2 Answers

From the documentation of FunctionalInterface :

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.

Since equals is from java.lang.Object, it's not counted. It's the compare method that relates to FunctionInterface.

like image 51
Mrinal Avatar answered Feb 10 '23 13:02

Mrinal


It is useful since if you add it and you have more than one method in the interface you will get a compile error. @FunctionalInterfaces are used to let Java know that this piece of code might be replaced with a lambda expression since every lambda is an implementation of some @FunctionalInterface. It helps the compiler know what is the method signature.

like image 23
Orr Levinger Avatar answered Feb 10 '23 13:02

Orr Levinger