/** instructor: Ray Ortigas * Date: Summer 2000 * http://www.dgp.toronto.edu/~rayo/tutorials/108/2000summer/ * * * A small program to test the classes in the Shape hierarchy. * * The Shape hierarchy looks like this: * * Shape * / \ * Rectangle Circle * | * Square */ public class ShapeDriver { public static void main(String[] args) { Shape[] a = new Shape[5]; a[0] = new Rectangle(3, 4); a[1] = new Square(5); a[2] = new Circle(4); a[3] = new Rectangle(5, 2); a[4] = new Circle(5); // Prints the string representations of each object in 'a'. // Note that the toString() methods for Rectangle, // Square and Circle are called, even though a is an array // of references to Shape objects. for (int i = 0; i != a.length; i++) { System.out.println(a[i]); } // Prints the area of each object in 'a'. for (int i = 0; i != a.length; i++) { System.out.println(a[i].getArea()); } // Moves each object in 'a' by a bit. for (int i = 0; i != a.length; i++) { a[i].move(2, 3); } // Prints the string representations of each object in 'a'. for (int i = 0; i != a.length; i++) { System.out.println(a[i]); } // The following line won't compile, because even though a[0] // refers to an Rectangle object, the reference is of type // Shape. The compiler looks at the Shape class to see if it has // 'exclusiveRectangleMethod()', finds that it doesn't, and // complains. //a[0].exclusiveRectangleMethod(); // These lines will work because we cast the reference. ((Rectangle)a[0]).exclusiveRectangleMethod(); ((Rectangle)a[1]).exclusiveRectangleMethod(); } }