user2565192 user2565192 -5 years ago 100
Java Question

Is it necessary for the comparable type implemented by subclass and superclass to be the same?

I have a class A

public class A<T> implements Comparable<A> {



And another class :

public class B<T> extends A implements Comparable<B> {



But it is giving an error, Comparable cannot be implemented with different arguments.

How should i solve it.?

Answer Source

When you implement Comparable<A>, you need to implement the compareTo method (if your class is not abstract):

public int compareTo(A obj) {

This method is also available in B, because B extends A.

But you try to implement Comparable<B>. If this would be possible, you will implement a new method:

public int compareTo(B obj) {

But due to type erasure, this is not possible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download