Why is it not necessary to override both methods of interface Comparator in Java

懵懂的女人 提交于 2019-12-21 02:46:30

问题


We know that it is necessary to implement all methods of an interface, if we want to make an object of that class. But why is it not necessary to implement both the methods compare() and equals() of interface Comparator in java?

I agree that the purpose is solved but even then why is it not mandatory to override equals() if we override compare()?


回答1:


Since all classes implicitly extend Object every implementation of a Comparator has an equals method, because every Object has one.

It would be the same if you define an interface with a toString() method.

 public interface ToString {
      public String toString();
 }

 public class SomeClass implements ToString {
     // toString implicitly implemented, because Object defines it
 }

When you look at the class it says "implements ToString" and this is true, isn't it?




回答2:


Because it is already overridden by java.lang.Object on every object you can create.




回答3:


Every object implicitly has an equals from Object (as every object is a sub-type of Object) - and since it's a virtual method, standard Java polymorphism takes over.


Now, Comparator#equals imposes an additional restriction, which is why it is specified as part of the interface.

..this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator.

However, since the coverse need to be true, then not overloading equals doesn't break the new requirement.

Note that it is always safe not to override Object.equals(Object).. [as then different comparator instances will never be equal].



来源:https://stackoverflow.com/questions/19582823/why-is-it-not-necessary-to-override-both-methods-of-interface-comparator-in-java

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