Search code examples
javacomparable

In java what does extending from a comparable mean


I see code like this

class A implements Comparable<A> {


}

What does this mean, what are the advantages and disadvantages of it?


Solution

  • It means that class is committed to respond to the methods defined by the "interface" Comparable.

    The advantage you have with this ( and any other "implements" declaration ) it that you can "abstract" the type of the object and code to the interface instead.

    Consider this

    class A implements Comparable {
        .... 
    }
    
    class B implements Comparable {
        .... 
    }
    
    
    class C implements Comparable {
        .... 
    }
    

    You then may code something that can use Comparable instead of a specific type:

    public void doSomethingWith( Comparable c ) {
    
           c.compareTo( other ); // something else...
    
    }
    

    And invoke it like:

      doSomethingWith( new A() );
    
      doSomethingWith( new B() );
    
      doSomethingWith( new C() );
    

    Because you don't really care what the type of the class is, you just care it does implement the interface.

    This ( program to the interface rather to the implementation ) is one of the most powerful techniques in OO programming world, because it promotes low-coupling.