问题描述
最近我开始探索 Java 8,我不太明白函数式接口"的概念,它对 Java 的 lambda 表达式的实现至关重要.有一个非常全面的指南,介绍了 Java 中的 lambda 函数,但我陷入了 定义函数式接口概念的章节.定义如下:
更准确地说,函数式接口被定义为任何只有一个抽象方法的接口.
然后他继续示例,其中之一是 Comparator
接口:
公共接口比较器{int比较(T o1,T o2);布尔等于(对象 obj);}
我能够测试我可以使用 lambda 函数代替 Comparator 参数并且它有效(即 Collections.sort(list, (a, b) -> a-b)
).
但是在 Comparator 接口中,compare
和 equals
方法都是抽象的,这意味着它有两个抽象方法.那么,如果定义需要一个接口来只有一个抽象方法,那么这怎么可能工作呢?我在这里错过了什么?
来自 您链接到的同一页面:
接口 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:
An then he proceeds to examples, one of which is Comparator
interface:
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:
I can't really say it better.
这篇关于“功能接口"的精确定义在 Java 8 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!