Search code examples
javainterfacecomparable

Why implement Comparable interface when you can define compareTo method in a class?


You can define the compareTo method in a class without implementing the Comparable interface. What are the benefits of implementing the Comparable interface?


Solution

  • The benefit of implementing the interface is that some methods specifically require object that implements the Comparable interface. It gives them a guarantee that the object you're passing has a compareTo method with the correct signature.

    There's no way in Java to have a method require that an object implement any given method (such as compareTo) in and of itself. To get around this, interfaces were created. Any time you have an object that you know is a Comparable, you also know you can call compareTo on it.