Uwe Allner Uwe Allner - 2 months ago 14x
Java Question

Why is it considered bad practice to define a covariant compareTo method?

Here's an example from my code:


abstract class AbstractBase implements Comparable<AbstractBase> {
private int a;
private int b;

public int compareTo(AbstractBase other) {
// compare using a and b


class Impl extends AbstractBase {
private int c;

public int compareTo(Impl other) {
// compare using a, b and c with c having higher impact than b in AbstractBase

FindBugs reports this as an issue. But why is that? What could happen?

And how would I correctly implement a solution?


Impl#compareTo(Impl) is not overriding AbstractBase#compareTo(AbstractBase) since they don't have the same signature. In other words, it won't be called when using Collections#sort for example.