“功能界面”的精确定义在Java 8中 [英] Precise definition of "functional interface" in Java 8

查看:167
本文介绍了“功能界面”的精确定义在Java 8中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始探索Java 8,我无法理解Java功能实现lambda表达式所必需的功能接口的概念。有一个非常全面的指南来介绍Java中的lambda函数,但是我被困在给出功能界面概念定义的章节。定义如下:

Recently I started exploring Java 8 and I can't quite understand the concept of "functional interface" that is essential to Java's implementation of lambda expressions. There is a pretty comprehensive guide to lambda functions in Java, but I got stuck on the chapter that gives definition to the concept of functional interfaces. The definition reads:


更准确地说,功能接口被定义为任何只有一个抽象方法的接口。

More precisely, a functional interface is defined as any interface that has exactly one abstract method.

然后他进入示例,其中一个是 Comparator interface:

An then he proceeds to examples, one of which is Comparator interface:


public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
} 


我能够测试我可以使用lambda函数代替Comparator参数,它可以工作(即 Collections.sort(list,(a,b) - > ab))。

I was able to test that I can use a lambda function in place of Comparator argument and it works(i.e. Collections.sort(list, (a, b) -> a-b)).

但是在Comparator界面中,比较等于方法是抽象的,这意味着它有两个抽象方法。那么,如果定义要求接口具有恰好一个抽象方法,那么它如何起作用呢?我在这里缺少什么?

But in the Comparator interface both compare and equals methods are abstract, which means it has two abstract methods. So how can this be working, if the definition requires an interface to have exactly one abstract method? What am I missing here?

推荐答案

来自您链接到的同一页面


接口比较器功能是因为虽然它声明了两个抽象方法,但其中一个 - equals-具有与Object中的公共方法相对应的签名。接口总是声明对应于Object的公共方法的抽象方法,但它们通常是隐式的。无论是隐式还是显式声明,这些方法都会从计数中排除。

The interface Comparator is functional because although it declares two abstract methods, one of these—equals— has a signature corresponding to a public method in Object. Interfaces always declare abstract methods corresponding to the public methods of Object, but they usually do so implicitly. Whether implicitly or explicitly declared, such methods are excluded from the count.

我真的不能说它更好。

修改:根据Maurice的评论更新至本页最新文本(谢谢!)

Updated to the most recent text of this page, per Maurice's comment (thanks!)

这篇关于“功能界面”的精确定义在Java 8中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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