ITEC 120 LAB 16 Back to Lab index page

The Comparable interface

Modify this Rational.java class file to implement the comparable interface.

To implement the Comparable interface, you must write a compareTo method for your object. As defined in the java.lang.Comparable documentation:

public int compareTo(Object o)
Compares this object with the specified object (o) for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object (o).

To perform the comparison, you will need to divide the numerator and denomonator of each rational object to get a floating point value. Use a tolerance of .0001 to compare the two floating point values. (So, if the two numbers are within .0001 of each other, you can say they are equal.)

Notice that the formal parameter for compareTo is an Object (and not a Rational). All objects are derived from the Object class, so you may pass any object to this method and its type will match Object. However, inside your method compareTo, you will want to access the instance data of o (lowercase letter o). o does not have instance data numerator, so you must cast o to be a Rational object, thus:

((Rational)o).numerator

The red parenthesis are necessary because you want to only cast o to be a Rational object. If you leave them out, you will be attempting to case o.numerator to be a Rational object, which you don't want. (numerator is an int).

Write a driver program to test the compareTo method that you wrote.

Once you have your program working, show your lab to the Peer Instructor to be checked off. Show an example how your compareTo method will work if two rational number objects are the same, if one rational number is less than another, and vice versa.