shape10

Main.java  [download]

/*
 * Note that the other *.java files don't change
 */

class Main {

	// The main program
	public static void main (String args[]) {

		/*
		 * Data definitions
		 */
		Shape[] s; //*1 Use an array
		s = new Shape[3]; //*2 Must declare AND instantiate array

		/*
		 * And now, instantiate the objects
		 */
		s[0] = new Rect (10, 10, 50, 50); //*3 Array elements can hold a Rect or Circle
		s[1] = new Rect (80, 10, 10, 100); //*3
		s[2] = new Circle (35, 90, 10); //*3

		/*
		 * "Draw" them
		 */
		for (int i=0; i<3; i++) s[i].draw(); //*4 Call irrespective of subclass
		
		for (int i=0; i<s.length; i++) s[i].draw(); //*5 Better way

		for (Shape item: s) item.draw(); //*6 Still better

		/*
		 * Compute and print total area
		 */
		float tot = 0;
		for (Shape item: s) tot += item.area(); //*6
		System.out.println ("Total area = " + tot);
	}
}