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

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

问题描述

最近我开始探索 Java 8,我不太明白函数式接口"的概念,它对 Java 的 lambda 表达式的实现至关重要.有一个非常全面的指南,介绍了 Java 中的 lambda 函数,但我陷入了 定义函数式接口概念的章节.定义如下:

<块引用>

更准确地说,函数式接口被定义为任何只有一个抽象方法的接口.

然后他继续示例,其中之一是 Comparator 接口:

<块引用>

公共接口比较器{int比较(T o1,T o2);布尔等于(对象 obj);}

我能够测试我可以使用 lambda 函数代替 Comparator 参数并且它有效(即 Collections.sort(list, (a, b) -> a-b)).

但是在 Comparator 接口中,compareequals 方法都是抽象的,这意味着它有两个抽象方法.那么,如果定义需要一个接口来只有一个抽象方法,那么这怎么可能工作呢?我在这里错过了什么?

解决方案

来自 您链接到的同一页面:

<块引用>

接口 Comparator 是函数式的,因为虽然它声明了两个抽象方法,但其中一个(equals)具有对应于 Object 中的公共方法的签名.接口总是声明对应于 Object 的公共方法的抽象方法,但它们通常是隐式的.无论是隐式声明还是显式声明,此类方法都被排除在计数之外.

我真的不能说得更好.

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.

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

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

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?

解决方案

From the same page you linked to:

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.

I can't really say it better.

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

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