4

Java 8 in Action book by Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft stats that:

public interface Adder{
    int add(int a, int b);
}
public interface SmartAdder extends Adder{
    int add(double a, double b);
}

SmartAdder isn’t a functional interface because it specifies two abstract methods called add (one is inherited from Adder).

In an other similar example in the book the following interface called as functional interface.

public interface ActionListener extends EventListener {
     void actionPerformed(ActionEvent e);
}

What makes the first example not functional interface compare to the second example?

codeme
  • 861
  • 2
  • 12
  • 29

2 Answers2

6

Because SmartAdder provides two method definitions (i.e. add is overloaded, not overridden):

  • int add(double a, double b);, and
  • int add(int a, int b); (from parent)

Conversely, EventListener is a marker interface, so ActionListener only provides one method definition, its own actionPerformed.

Mena
  • 47,782
  • 11
  • 87
  • 106
5

EventListener is an empty interface, so ActionListener which extends it has just one method - public void actionPerformed(ActionEvent e). Therefore it is a functional interface.

On the other hand, SmartAdder has two abstract methods (int add(int a, int b) and int add(double a, double b)), so it can't be a functional interface.

Eran
  • 387,369
  • 54
  • 702
  • 768