Page 224 - AP Computer Science A, 7th edition
P. 224
Classes written for objects that need to be compared should implement Comparable.
Example
The abstract Shape class defined previously is modified to implement the Comparable interface:
public abstract class Shape implements Comparable {
private String name;
//constructor
public Shape(String shapeName) { name = shapeName; }
public String getName() { return name; }
public abstract double area(); public abstract double perimeter();
public double semiPerimeter() { return perimeter() / 2; }
public int compareTo(Object obj) {
final double EPSILON = 1.0eā15; bigger than
//slightly
//machine precision Shape rhs = (Shape) obj;
double diff = area() ā rhs.area(); if (Math.abs(diff) <= EPSILON ā Math.abs(area()))
return 0; //area of this shape equals area
of obj
else if (diff < 0)
return ā1; //area of this shape less than
area of obj else
return 1; //area of this shape greater than area of obj