Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept of functional interface

When I'm shooting a glance at lambda expressions, the book touches on a functional interface that has only one abstract method. My issue addresses on that quiz question

/* Which of these interfaces are functional interfaces? */
public interface Adder{
   int add(int a, int b);
}
public interface SmartAdder extends Adder{
   int add(double a, double b);
}
public interface Nothing{
}

I know the last one is not, but I think the first and second ones should be functional interface. But the book says second one is not. Why? Doesn't it overrides add method? So even in second, isn't there only one abstract method?

like image 340
snr Avatar asked Jan 04 '23 22:01

snr


2 Answers

An easy way to find out would be to try to define a class that implements SmartAdder. The compiler will tell you you need to implement both add(int, int) and add(double, double).

It's understandable that you thought add(double, double) would override add(int, int), but they are in fact separate methods, and could potentially have totally unrelated implementations.

If SmartAdder had defined a default implementation of add(int, int) it would be a functional interface still:

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

   default int add(int a, int b) {
     return add((double)a, (double)b); // this calls the double method instead
  }
}

You may also have come across the @FunctionalInterface annotation - this can be placed on an interface to enforce at compile-time that the interface has exactly one abstract method. If SmartAdder was annotated with @FunctionalInterface the interface itself would not compile.

like image 68
dimo414 Avatar answered Jan 06 '23 12:01

dimo414


SmartAdder has two methods. The method signatures are different. Functional Interface can have only one method.

like image 41
cosmos Avatar answered Jan 06 '23 10:01

cosmos