We can also use abstract classes to group together classes that are at different, incomparable points in the class hierarchy but share some common properties. For example, we may want to group together all classes whose objects can be compared using a linear order. Any such class can then serve as a valid input to a sort function, using the comparison method defined within the class whenever the sort function needs to compare two objects.
For instance, we might have a definition such as
abstract class Comparable{ public abstract int cmp(Comparable s); // return -1 if this < s, 0 if this == 0, +1 if this > s }
Now, we can sort any array of objects that extend the class Comparable:
class Sortfunctions{ public static void quicksort(Comparable[] a){ ... // Usual code for quicksort, except that // to compare a[i] and a[j] we use a[i].cmp(a[j]) // (Why is this method declared to be static?) } ... }
If we want to make the objects of a class sortable using one of the Sortfunctions, we write
class Myclass extends Comparable{ double size; // some quantity that can be used to compare // two objects of this class ... public int cmp(Comparable s){ if (s instanceof Myclass){ // compare this.size and ((Myclass) s).size // Note the cast to access s.size ... } } }