// Shape.java - Shape abstract superclass // Suzanne Balik, 11 Sep 2001 // // Added compareTo and equals methods based on // Barron's How to Prepare for the AP Computer Science // Exam by Roselyn Teukolsky public abstract class Shape implements Comparable{ private int idNumber; public Shape(int idNumber) { this.idNumber = idNumber; } public final int getIdNumber() { return idNumber; } public abstract double area(); public abstract String type(); //Implement the compareTo method in the //Comparable interface public int compareTo(Object obj) { //Define a very small range to use to determine //if the shapes have the "same" area final double EPSILON = 1.0e-15; //Cast the Object to a Shape Shape otherShape = (Shape) obj; //Calculate the difference between the //area of "this" Shape and the "other" Shape double diff = area() - otherShape.area(); if (Math.abs(diff) < EPSILON * Math.abs(area())) return 0; //Both Shapes have ~same area. else if (diff < 0) //"this" Shape has a smaller area return -1; //than the "other" Shape else //"this" shape has a larger area return 1; //than the "other" Shape } //Override the equals method inherited from the //Object class public boolean equals(Object obj) { //Define a very small range to use to determine //if the shapes have the "same" area final double EPSILON = 1.0e-15; //Cast the Object to a Shape Shape otherShape = (Shape) obj; //Calculate the difference between the //area of "this" Shape and the "other" Shape double diff = area() - otherShape.area(); if (Math.abs(diff) < EPSILON * Math.abs(area())) return true; //Both Shapes have ~same area. else return false; //The Shapes have different areas. } }