public boolean precedes (Sortable other)The method precedes returns true if and only if its implicit object precedes other. Once we have a method that defines criteria for ordering Sortable objects, we can then write a sort for such objects.
|
interface Sortable { public boolean precedes (Sortable other) ; }Notice in the definition the word interface instead of class. Notice also that the method of the interface has no body. This is characteristic of all interfaces; their methods never have bodies. All that the definition does is, in a sense, layout the framework for what would be required of any class that wants to be considered to be of type Sortable. For the second part, for each class that we want to be designated as Sortable, we must provide a precedes method with the signature given in the interface. This method must define how to determine the ordering of objects of that type. The next example illustrates how we can do this.
|
Fraction f = (Fraction)s;If we were writing a precedes method for a Widget class, we would have to cast the Sortable parameter to an object of type Widget. With this revised definition of the Fraction class, we can now use the selectSort method of Example 1 to sort an array of Fraction objects because Fraction objects can also be considered as Sortable objects. If our program contained other classes that implemented Sortable, then arrays of objects of these classes could also be sorted using exactly the same method. This idea is such a good one that a form of it is actually implemented in Java. In the java.lang package, there is an interface called Comparable that contains the header of a single method called compareTo with the signature
public int compareTo (Object 0)Any class implementing the Comparable interface must supply a compareTo method that accepts some kind of Object as a parameter and returns an int value as specified in the following table
Relationship Between Objects Value Returned implicit object precedes explicit object some negative integer implicit object equals explicit object zero implicit object follows explicit object some positive integer |
|
|
|
Original Values 3/4 7 Jonathan 1/2 5 Callum 2/3 2 Melissa Sorted Values 1/2 2 Callum 2/3 5 Jonathan 3/4 7 Melissa |
|