Java函数式接口的一个疑惑:为什么Comparator接口有两个抽象方法compare和equals,Comparator还是一个函数式接口?(@FunctionalInterface)

    首先,每一个函数式接口都可以使用一个注解@FunctionalInterface。那么我们先去看一看该注解的javadoc:

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
 
Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
 
If a type is annotated with this annotation type, compilers are required to generate an error message unless:
• The type is an interface type and not an annotation type, enum, or class.
• The annotated type satisfies the requirements of a functional interface.
 
However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a Functional Interface annotation is present on the interface declaration.

    现在我们来人工纯手动翻译一下:
        根据Java语言规范的定义,一个使用了该注释的接口类型声明将被视为一个函数式接口。从概念上讲,一个函数式接口有且只有一个抽象方法。由于默认方法已经有了实现,所以它们不是抽象方法。如果一个接口中声明的抽象方法是重写了超类Object类中任意一个public方法,那么这些抽象方法并不会算入接口的抽象方法数量中。因为任何接口的实现都会从其父类Object或其它地方获得这些方法的实现。
        注意:函数式接口的实现可以由Lambda表达式方法引用构造器引用等方式实现。
        如果一个类型使用了该注释,那么编译器将会生成一个错误信息,除非这个类型是一个接口类型,而不是一个注释类型、枚举或类。同时使用该注释的接口满足函数式接口的要求,即一个函数式接口有且只有一个抽象方法。
        但是编译器会将所有定义为函数式接口(满足函数式接口要求)的接口视为函数式接口,而不管这个接口声明中是否使用了函数式接口的注释(即@FunctionalInterface)。
    从中我们可以知道:

  1. 一个函数式接口有且只有一个抽象方法。
  2. 默认方法不是抽象方法,因为它们已经实现了。
  3. 重写了超类Object类中任意一个public方法的方法并不算接口中的抽象方法。

    所以虽然Comparator接口中有两个抽象方法compare和equals,但equals并不算入接口中的抽象方法,所以Comparator接口还是满足函数式接口的要求,Comparator接口是一个函数式接口。

Java - Lambda表达式 / 方法引用 / 构造器引用 / 数组引用(多种情况举例说明)

猜你喜欢

转载自blog.csdn.net/H_X_P_/article/details/105030682
今日推荐