关于函数式接口Comparator的疑惑

qq_27494919 2015-07-22 10:23:22
函数式接口代表的是只能由一个抽象方法,多个类方法或多个默认方法,但是查阅Comparator接口的源码,发现它有两个抽象方法(compare和equals方法),但它又使用了@FunctionalInterface注解,感到有点疑惑?
...全文
420 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
隹灬 2019-05-09
  • 打赏
  • 举报
回复
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或其他地方。 如果接口声明了一个覆盖java.lang.Object的全局方法之一的抽象方法,那么它不会计入接口的抽象方法数量中,因为接口的任何实现都将具有java.lang.Object或其他地方的实现。
隹灬 2019-05-09
  • 打赏
  • 举报
回复
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或其他地方。 如果接口声明了一个覆盖java.lang.Object的全局方法之一的抽象方法,那么它不会计入接口的抽象方法数量中,因为接口的任何实现都将具有java.lang.Object或其他地方的实现。
山河已无恙 2019-02-01
  • 打赏
  • 举报
回复
函数式接口中可以额外定义多个抽象方法,但这些抽象方法签名必须和Object的public方法一样
接口最终有确定的类实现, 而类的最终父类是Object。 因此函数式接口可以定义Object的public方法。
如以下的接口依然是函数式接口:
@FunctionalInterfacepublic
interface ObjectMethodFunctionalInterface {
void count(int i);
String toString(); //same to Object.toString
int hashCode(); //same to Object.hashCode
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类型。
在百度贴吧看到的,----id=“画_夜”
ZGQ_C 2018-03-23
  • 打赏
  • 举报
回复
引用 2 楼 huntor 的回复:
equals是Object提供的
为啥是Object 提供的就可以
huntor 2015-07-22
  • 打赏
  • 举报
回复
equals是Object提供的
huntor 2015-07-22
  • 打赏
  • 举报
回复
equals是Object提供的

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧