Lets turn our attention to making a list of fractions sortable by the standard Java sorting method
Collections.sort. In Python, we would just need to implement the
__cmp__ method. But in Java we cannot be that informal. In Java, things that are sortable must be
Comparable. Your first thought might be that
Comparable is superclass of
Number, but that is actually not the case. Java only supports
single inheritance, that is, a class can have only one parent. Although it would be possible to add an additional layer to the class hierarchy it would also complicate things dramatically, because not only are
Numbers comparable, but
Strings are also
Comparable as would many other types. For example, we might have a
Student class and we want to be able to sort students by their GPA. But
Student might already extends the class
Person for which there would be no natural comparison method.
Java’s answer to this problem is the
Interface mechanism. Interfaces are like a combination of “inheritance” and “contracts” all rolled into one. An interface is a
specification that says any object that claims it implements this interface must provide the following methods. It sounds a little bit like an abstract class, however it is outside the inheritance mechanism. You can never create an instance of
Comparable. Many objects, however, do implement the
Comparable interface. What does the
Comparable interface specify?
The
Comparable interface says that any object that claims to be
Comparable must implement the
compareTo method. Here is an excerpt from
the official documentation for the
compareTo method as specified by the
Comparable interface.
Listing 6.6.1 shows the excerpt.