As everybody knows, Java 8 have introduced functional programming to Java developers.
Such interfaces as Comparator
, Runnable
, Callable
and so on are functional.
As follows from definition: functional interfaces are interfaces that have only a single abstract method.
But for example the same interface Comparator
have more than one abstract methods:
int compare(T o1, T o2);
boolean equals(Object obj); // inherited from Object class
// and a lot of concrete methods more
Well, is there any strict rule of how to determine if the interface is functional, so that it can be used as the assignment target for a lambda expression or method reference?
From the JLS §9.8 (highlighting mine):
A functional interface is an interface that has just one abstract method (aside from the methods of Object)
The rationale is
to use the interface, you have to instantiate it. Every instantiation necessarily inherits from Object
, and thus implements these abstract methods anyway.
The other method -
boolean equals(Object)
- is an explicit declaration of an abstract method that would otherwise be implicitly declared, and will be automatically implemented by every class that implements the interface.
As a functional interface, it is very unlikely that you want to call a method that is defined by Object
. Thus, these methods do not count when searching for a method to call (because the method of functional interfaces can be called without naming that method).
This is to allow functional treatment of an interface like
java.util.Comparator<T>
that declares multiple abstract methods of which only one is really "new" -int compare(T,T)
.
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