Suppose a Superclass implements Comparable<Superclass>, such that Arrays.sort(ArrayOfSuperInstances); uses this compareTo(Superclass other) method to sort. Does this guarantee that an array of instances of Subclass extends Superclass will sort in the same way using Arrays.sort(ArrayOfSubInstances); ? (Assuming the compareTo is not overloaded in the subclass definition)
Or in other words, will Subclass by default inherit the compareTo method of its Superclass , so that one can blindly use Arrays.sort() knowing they will be sorted as superclasses would be?
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
compareToin 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 overridescompareToin 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
compareTocompares the two squares’ sizes:…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 implementsComparable<Square>), but you can use reflection to get around this: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: