// Ch9Demo1
public class Ch9Demo1
{
public static void main(String[] args)
{
Student student1 = new Student(4.0, "alfred", 72);
Student student2 = new Student(3.4, "Christopher", 63);
if (student1.compareTo(student2) > 0)
System.out.println("alfred is greater than Christopher");
else if (student1.compareTo(student2) < 0)
System.out.println("alfred is less than Christopher");
else
System.out.println("tie");
}
}
// ***************************************************
// Student.java
public class Student implements Comparable
{
public Student(double gpa, String name, int height)
{
myGPA = gpa;
myName = name;
myHeight = height;
}
public int compareTo(Object explParam)
{
if (this.myGPA > ((Student) explParam).myGPA)
return 1;
else if (this.myGPA < ((Student) explParam.)myGPA)
return -1;
return 0;
// or
// return this.myName.compareTo(((Student) explParam).myName);
// to compare student's by name using the String class' compareTo
// method instead of comparing by GPA
}
private double myGPA;
private String myName;
private int myHeight; // in inches
}