Yes -- that is the whole principle behind polymporphism, and specifically the Liskov substitution principle. Basically, if A is a subclass of B, then you should be able to use A anywhere you'd be able to use B, and it should essentially act the same as any other instance of B (or other subclasses of B).
So, not only will it happen, but it's almost always what you want to happen. It's usually wrong to compareTo
in the subclass.
Why? Well, part of the Comparable<T>
contract is that comparison is transitive. Since your superclass will presumably not know what its subclasses are doing, if a subclass overrides compareTo
in such a way that it gives an answer different than its superclass, it breaks the contract.
So for instance, let's say you have something like a Square and a ColorSquare. Square's compareTo
compares the two squares' sizes:
@Override
public int compareTo(Square other) {
return this.len - other.len;
}
...while ColorSquare also adds a comparison for color (let's assume colors are Comparable). Java won't let you have ColorSquare implement Comparable<ColorSquare>
(since its superclass already implements Comparable<Square>
), but you can use reflection to get around this:
@Override
public int compareTo(Square other) {
int cmp = super.compareTo(other);
// don't do this!
if (cmp == 0 && (other instanceof ColorSquare)) {
ColorSquare otherColor = (ColorSquare) other;
cmp = color.compareTo(otherColor.color);
}
return cmp;
}
This looks innocent enough at first. If both shapes are ColorSquare, they'll compare on length and color; otherwise, they'll only compare on length.
But what if you have:
Square a = ...
ColorSquare b = ...
ColorSquare c = ...
assert a.compareTo(b) == 0; // assume this and the other asserts succeed
assert a.compareTo(c) == 0;
// transitivity implies that b.compareTo(c) is also 0, but maybe
// they have the same lengths but different color!
assert b.compareTo(c) == 1; // contract is broken!
Comparable
interface). Is this LSP adhered to throughout the whole Java package hierarchy, or are there some exceptions? – Enciso