How can Comparator be a Functional Interface when it has two abstract methods? [duplicate]

大兔子大兔子 提交于 2019-12-18 03:50:34

问题


In Java 8, the @FunctionalInterface annotation is introduced to denote any interface that has exactly one abstract method as a functional interface. One of the reason for its introduction is to indicate the user (programmer), that lambda expression can be used in context of a functional interface.

The Comparator interface is annotated with @FunctionalInterface. But, two methods are abstract.

int compare(T o1, T o2);

and

boolean equals(Object obj);

In the docs of FunctionalInterface, it is clearly mentioned as

Conceptually, a functional interface has exactly one abstract method.

Isn't the equals method not considered as abstract here?


回答1:


The docs also state:

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.

And since equals is one of those methods, the "abstract method count" of the interface is still 1.




回答2:


Also from the FunctionalInterface documentation page:

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. [emphasis mine]

Since equals is a public method of Object, this statement applies; thus, for Comparator only the compare method contributes to the abstract method count.

Other notable methods to which this rule applies are toString and hashCode.



来源:https://stackoverflow.com/questions/43616649/how-can-comparator-be-a-functional-interface-when-it-has-two-abstract-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!