I have a superclass which implements the Comparable Interface and overrides the compareTo() method. One subclass of this superclass has to implement it’s own compareTo() method but I’m not able to override the compareTo() method of the superclass due to the name clash error.
public abstract class Superclass<T> implements Comparable<T> {
public int compareTo(T bo) { };
}
public class Subclass extends Superclass<Subclass> {
public <T> int compareTo(T bo) { }; // I get the name clash error here
}
To solve this problem I tried to make the subclass generic too (see: Java Generics name clash, method not correctly overridden), but either I did it wrong or this doesn’t work:
public abstract class Superclass<T> implements Comparable<T> {
public int compareTo(T bo) { };
}
public class Subclass<T> extends Namable<Subclass<?>> {
public int compareTo(T bo) { }; // I get the name clash error here
}
So, how can I override the compareTo() method of Superclass?
I think you have a more general design issue here. Namely, why do you want to implement
compareToin the base class? In practice, this almost always leads to problems down the line.Consider
If you have two
Superclassinstances (whose superclass portions are identical, but the subclass portions may not be), how can you compare them usingSuperclass.compareTo? If you don’t take concrete subclasses into account, the result of the comparison is 0, incorrectly. If you try to directly compare objects of different subclasses, you will fail with a runtime exception. If you try to be clever and check the runtime types of the objects before trying to directly compare them, again you need to throw some sort of runtime exception instead of returning a valid-looking result.I think it would be better to reverse the schema and implement
compareToonly in concrete subclasses where the compiler may ensure that the method is called with the right type of parameter. If you are worried about duplicating code between subclasses, you may pull it up into aprotected finalmethod in the superclass.Update
Code example: