Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
kal Avatar asked Mar 01 '23 11:03

kal


2 Answers

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.

like image 163
OscarRyz Avatar answered Mar 11 '23 10:03

OscarRyz


Implementing a comparable interface means that A can be compared with other instances of A.

Many operations in java that involve sorting use the methods defined in the Comparable interface to determine if instances of A are greater then less or equal to other instances.

By implementing these methods you are able to use a lot of handy features such as java sort, use instances of A as keys for binary trees, and more.

like image 32
Ori Avatar answered Mar 11 '23 08:03

Ori