- student.Student
public boolean equals(Student student) // overloading equals()
{
return getNumber() == student.getNumber();
}
- Student implements Comparable
public boolean equals(Object obj) // overriding Object.equals()
{
if(obj instanceof Student)
{
Student student = (Student)obj;
return getNumber() == student.getNumber();
} else
{
return false;
}
}
public int compareTo(Object obj) // overriding Comparable.compareTo()
throws ClassCastException
{
int i = getGrade();
int j = ((Student)obj).getGrade();
return i != j ? i >= j ? 1 : -1 : 0;
}
- it is your job to ensure correct reference is used e.g.
in "((Student)obj).getGrade()", obj is indeed a Student object which has the getGrade() method or else ClassCastException will be resulted
- handling ClassCastException
Range ran = new Range();
Account acc = new Account();
try {
if (ran.equals((Range) acc)) {
stdOut.println("Execution would not get here...");
}
} catch(ClassCastException cce) {
stdOut.println(cce.toString());
}
- making use of Inheritance and Polymorphism Store anything (Collection) and Sort everything (Comparable)