函数式接口Comparator的疑惑

函数式接口表明的是只能由一个抽象方法,多个类方法或多个默认方法,可是查阅Comparator接口的源码,发现它有两个抽象方法(compare和equals方法),但它又使用了@FunctionalInterface注解,感到有点疑惑。java

public @interface FunctionalInterface 官方文档这样说: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.
若是接口声明了一个覆盖java.lang.Object的全局方法之一的抽象方法,那么它不会计入接口的抽象方法数量中,由于接口的任何实现都将具备java.lang.Object或其余地方的实现。函数

函数式接口中能够额外定义多个抽象方法,但这些抽象方法签名必须和Object的public方法同样。.net

接口最终有肯定的类实现, 而类的最终父类是Object。 所以函数式接口能够定义Object的public方法。接口

如如下的接口依然是函数式接口:文档

@FunctionalInterfaceget

public interface ObjectMethodFunctionalInterface {源码

void count(int i);hash

String toString(); //same to Object.toStringio

int hashCode(); //same to Object.hashCodeclass

boolean equals(Object obj); //same to Object.equals

为何限定public类型的方法呢?由于接口中定义的方法都是public类型的。 举个例子,下面的接口就不是函数式接口:

interface WrongObjectMethodFunctionalInterface {

void count(int i);

Object clone(); //Object.clone is protected

由于Object.clone方法是protected类型。

相关文章
相关标签/搜索