shape7

Shape.java  [download]

/*
 * Definition of superclass Shape
 */

abstract class Shape {
	// protected, not private, cause is used by our subclasses
	protected int x, y; //*1 Common to Rect and Circle

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

Rect.java  [download]

/*
 * Definition of subclass Rect
 */

class Rect extends Shape {

	private int wid, ht; //*2 ivars defined by Rect

	public Rect (int xin, int yin, int widin, int htin) {
		x = xin; y = yin; //*1 ivars inherited from Shape
		wid = widin; ht = htin; //*2
	}

	public void setSize (int widin, int htin) {
		wid = widin; ht = htin; //*2
	}

	public void draw() {
		System.out.println ("Drawing rectangle at " 
			+ x + ", " + y + ", " + wid + ", " + ht);
	}

	public float area() {
		return (float) (wid * ht);
	}
}

Circle.java  [download]

/*
 * Definition of class circle
 */

class Circle extends Shape {

	private int rad;

	// N.B. This shows how you can use same var name in ivar and arg
	public Circle (int x, int y, int rad) { //*1 How to use same var name in ivar and arg
		this.x = x; this.y = y; //*1
		this.rad = rad; //*1
	}

	public void setSize (int rad) { //*1
		this.rad = rad; //*1
	}

	public void draw() {
		System.out.println ("Drawing circle at " + x + ", " + y
			+ ", radius = " + rad);
	}

	public float area() {
		return (float) (rad * rad * 3.14159);
	}
}