shape9

Main.java  [download]

/*
 * Just a main program for testing our objects
 * this time exploiting polymorphism
 * Note that the other *.java files don't change
 */

class Main {

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

		/*
		 * Data definitions
		 */
		Shape s1, s2, s3; //*1 Declare as Shape not Rect or Circle

		/*
		 * And now, instantiate the objects
		 */
		s1 = new Rect (10, 10, 50, 50); //*2 Shape var can hold a Rect or Circle
		s2 = new Rect (80, 10, 10, 100); //*2
		s3 = new Circle (35, 90, 10); //*2

		/*
		 * "Draw" them
		 */
		s1.draw (); //*3 Can call irrespective of subclass
		s2.draw (); //*3
		s3.draw (); //*3

		/*
		 * Compute and print total area
		 */
		System.out.println ("Total area = " + 
			(s1.area() + s2.area() + s3.area())); //*3
	}
}

Shape.java  [download]

/*
 * Definition of superclass Shape
 */

abstract class Shape { //*2 Abstract class
	// protected, not private, cause is used by our subclasses
	protected int x, y; //*3 Protected, not private, cause is used by our subclasses

	public void setPos (int xin, int yin) {
		x = xin; y = yin;
	}

	abstract public void draw(); //*1 Add abstract functions to Shape

	abstract public float area(); //*1
}