Example of Abstract Class (Shape hierarchy) handout #29
Abstract Class Shape.java
-------------------------
// The Shape class is an abstract class that serves as the superclass of a
// family of Shape classes. It implements the Comparable interface, ordering
// shapes by their area.
public abstract class Shape implements Comparable {
private String name;
public Shape(String name) {
this.name = name;
}
public abstract double area();
public final int compareTo(Shape other) {
double difference = area() - other.area();
if (difference < 0)
return -1;
else if (difference == 0)
return 0;
else // difference > 0
return 1;
}
public final String toString() {
return name + " of area " + area();
}
}
Class Circle.java
-----------------
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
super("circle");
this.radius = radius;
}
public double area() {
return Math.PI * radius * radius;
}
}
Class Rectangle.java
--------------------
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
super("rectangle");
this.length = length;
this.width = width;
}
public double area() {
return length * width;
}
}
Class Square.java
-----------------
public class Square extends Shape {
private double length;
public Square(double length) {
super("square");
this.length = length;
}
public double area() {
return length * length;
}
}
Testing Code ShapeTest.java
---------------------------
import java.util.*;
public class ShapeTest {
public static void main(String[] args) {
Shape[] data = {new Square(12), new Rectangle(15, 3.2),
new Circle(8.4), new Circle(1.5), new Square(8.7),
new Rectangle(7.2, 3.2), new Square(2.4),
new Circle(3.7), new Circle(7.9)};
for (Shape s : data)
System.out.println(s);
System.out.println();
Arrays.sort(data);
for (Shape s : data)
System.out.println(s);
}
}
Output of Testing Code
----------------------
square of area 144.0
rectangle of area 48.0
circle of area 221.6707776372958
circle of area 7.0685834705770345
square of area 75.68999999999998
rectangle of area 23.040000000000003
square of area 5.76
circle of area 43.00840342764427
circle of area 196.066797510539
square of area 5.76
circle of area 7.0685834705770345
rectangle of area 23.040000000000003
circle of area 43.00840342764427
rectangle of area 48.0
square of area 75.68999999999998
square of area 144.0
circle of area 196.066797510539
circle of area 221.6707776372958