Is it ugly design that I overload a method depending on whether the argument is subtype or supertype?
I intend to implent a super class A and a subclass B, and the objects can compare with each other.
compareTo is overloaded twice both in class A and class B, and the code seems a little messy. It feels like ugly design. I'm not sure if there is a more elegant approach.
class A implements Comparable<A> {
private Integer x;
public A(Integer i) {
x = i;
}
public Integer getX() {
return x;
}
public int compareTo(A other) {
return x.compareTo(other.getX());
}
public int compareTo(B other) {
return x.compareTo(other.getX() + other.getY());
}
}
class B extends A {
private Integer y;
public B(Integer a, Integer b) {
super(a);
y = b;
}
public Integer getY() {
return y;
}
@Override
public int compareTo(A other) {
return Integer.compare(this.getX() + y, other.getX());
}
@Override
public int compareTo(B other) {
return Integer.compare(this.getX() + y, other.getX() + other.getY());
}
}