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

前端 未结 3 523
别那么骄傲
别那么骄傲 2021-02-09 22:17

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

相关标签:
3条回答
  • 2021-02-09 22:44

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

    0 讨论(0)
  • 2021-02-09 23:01

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

    0 讨论(0)
  • 2021-02-09 23:06

    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?

    0 讨论(0)
提交回复
热议问题