Why is it not necessary to override both methods o

2019-03-21 11:35发布

问题:

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].