6

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?

px06
  • 2,256
  • 1
  • 27
  • 47
DimaSan
  • 12,264
  • 11
  • 65
  • 75
  • 1
    `boolean equals(Object obj)` is not inherited from Object class. If it was, it wouldn't be abstract. Interface is not a subtype of Object. โ€“ Marko Topolnik Sep 23 '16 at 09:00

1 Answers1

7

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

  1. 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.

  2. 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).

Martin Nyolt
  • 4,463
  • 3
  • 28
  • 36
  • 1
    Having only abstract method excluding the methods of `Object` therefore may it have any number of non-abstract methods? โ€“ DimaSan Sep 23 '16 at 08:39
  • 2
    Yes, the non-abstract methods are ignored when determining if an interface is functional. โ€“ Martin Nyolt Sep 23 '16 at 08:45