I see code like this
class A implements Comparable<A> {
}
What does this mean, what are the advantages and disadvantages of it?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With