//An interface used to compare two objects. import java.lang.Comparable; /** * A test for the compareTo() method for several classes * @author William McDaniel Albritton */ public class TestComparable{ /**main() method: begins program * @param arguments is not used */ public static void main(String[] arguments) { //compare two Integers Integer number1 = new Integer(7); Integer number2 = new Integer(3); TestComparable.output(number1, number2); //compare two Strings //note that A < Z, for alphabetical ordering String fruit = new String("apple"); String animal = new String("zebra"); TestComparable.output(fruit, animal); //compare two Fractions Fraction oneHalf = new Fraction(1, 2); Fraction twoFourths = new Fraction(2, 4); TestComparable.output(oneHalf, twoFourths); //compare two Names Name name1 = new Name("Zeus", "Aoki"); Name name2 = new Name("Sally", "Suzuki"); TestComparable.output(name1, name2); //compare two ThreeNames ThreeNames name3 = new ThreeNames("Sally", "Grace", "Suzuki"); ThreeNames name4 = new ThreeNames("Sally", "Ann", "Suzuki"); TestComparable.output(name3, name4); try{ //compare a Name to a Fraction Fraction fiveSixths = new Fraction(5, 6); Name name56 = new Name("Isoroku", "Yamamoto"); TestComparable.output(fiveSixths, name56); } catch(ClassCastException exception){ System.out.println(exception); } } /** * Outputs the toString() method and compareTo() method for two objects * @param object1 is the 1st object * @param object1 is the 2nd object */ public static void output(Comparable object1, Comparable object2){ System.out.println("object1 = " + object1); System.out.println("object2 = " + object2); System.out.println("object1.compareTo(object2) = " + object1.compareTo(object2)); }//end of method }//end of class /* program output: object1 = 7 object2 = 3 object1.compareTo(object2) = 1 object1 = apple object2 = zebra object1.compareTo(object2) = -25 object1 = 1 / 2 object2 = 2 / 4 object1.compareTo(object2) = 0 object1 = Aoki, Zeus object2 = Suzuki, Sally object1.compareTo(object2) = -18 object1 = Suzuki, Sally Grace object2 = Suzuki, Sally Ann object1.compareTo(object2) = 6 object1 = 5 / 6 object2 = Yamamoto, Isoroku java.lang.ClassCastException: Name cannot be cast to Fraction */