Concept of functional interface

自闭症网瘾萝莉.ら 提交于 2019-11-30 23:27:22

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.

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

interface SmartAdder overloads, not overrides interface Adder. That's because the name is the same name, but parameters types are different. Therefore, it has 2 functions. To be a functional interface it needs to have only one function.

==> Only interface Adder is a functional interface.

In Java, a method in a subtype overrides a method of a parent type when it has the same signature. Signature means both name and arguments of the method. In particular, arguments must be of the same exact type and must be declared in the same exact order in both methods, i.e. the types of the arguments of the method declared in the subtype can't be subtypes or types wider than the types of the arguments declared in the parent type's method.

So, in your SmartAdder interface, the method with signature add(double a, double b) does not override the method add(int a, int b) of your Adder interface, because double is wider than int. When a type has two or more methods with the same name but with different arguments, it is called method overloading, and it's totally different than method overriding.

This is why SmartAdder ends up having two abstract methods, hence it's not a functional interface (which requires the type to have only one abstract method).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!