Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to implement Comparable<super class of X> instead of Comparable<X>?

Tags:

java

generics

class A { ... }


class B extends A implements Comparable<A> {
    int compareTo(A aobject) { ... }
}

Usually we implement Comparable with a type-parameter of B. But java allows using a super class, as well.

Is there a scenario where I really need to do something like this?

like image 461
Rahul Kurup Avatar asked Oct 20 '22 05:10

Rahul Kurup


1 Answers

For instance if you have also:

Class C extends A implements Comparable<A> {

int compareTo(A aobject) {
/* Implementations */
}

you could compare objects of class B and C together either with c.compareTo(b) or with b.compareTo(c).

like image 138
Renzo Avatar answered Oct 22 '22 00:10

Renzo