功能界面的概念 [英] Concept of functional interface

查看:124
本文介绍了功能界面的概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我瞥一眼lambda表达式时,本书触及了一个只有一个抽象方法的功能界面。我的问题涉及该测验问题

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?

推荐答案

一个简单的方法是找出来尝试定义一个实现 SmartAdder 的类。编译器会告诉你需要实现 add(int,int) add(double,double)

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

你认为 add(double,double)会覆盖 add(int)是可以理解的,int),但它们实际上是单独的方法,并且可能具有完全不相关的实现。

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.

如果 SmartAdder 定义了一个默认 的实现add(int,int)会仍功能界面:

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
  }
}

你也可以已经遇到 @FunctionalInterface 注释 - 这可以放在接口上,以便在编译时强制执行接口只有一个抽象方法。如果 SmartAdder 使用 @FunctionalInterface 进行注释,则接口本身将无法编译。

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.

这篇关于功能界面的概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆