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.
Methods From Object Class in Functional Interfaces How is it a functional interface when it has two abstract methods? Because equals() method signature matches from Object, and the compare() method is the only remaining abstract method, hence the Comparator interface is a functional interface.
Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.
Answer: Yes, comparable is a functional interface. It declares a single abstract method, compareTo ().
The Comparator only has one abstract method int compare(T o1, T o2) , and it meet the definition of functional interface.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With