When implementing the Comparable<T>.compareTo
method, the parameter’s type has to match the type used in the
Comparable
declaration. When a different type is used this creates an overload instead of an override, which is unlikely to be the
intent.
This rule raises an issue when the parameter of the compareTo
method of a class implementing Comparable<T>
is not
same as the one used in the Comparable
declaration.
Noncompliant code example
public class Foo {
static class Bar implements Comparable<Bar> {
public int compareTo(Bar rhs) {
return -1;
}
}
static class FooBar extends Bar {
public int compareTo(FooBar rhs) { // Noncompliant: Parameter should be of type Bar
return 0;
}
}
}
Compliant solution
public class Foo {
static class Bar implements Comparable<Bar> {
public int compareTo(Bar rhs) {
return -1;
}
}
static class FooBar extends Bar {
public int compareTo(Bar rhs) {
return 0;
}
}
}