Homework #2 Assignment

Consider the Rectangle class below. Create a Square class that extends the Rectangle class (but do not modify the Rectangle class). Do not define any additional attributes in the Square class; use the ones inherited from Rectangle. The Square class must implement a two-argument constructor whose first argument is the width/height of the square, while the second argument is the square's name. The Square class must override the toString() method so that it creates a String representation of the Square such that the String returned on calling the method returns something like: "Square s1: width=2.50, area=6.25, perimeter=10.00".

Use the Driver class below the Rectangle class to test your implementation.

/**
 * This class represents a rectangle
 */
public class Rectangle {
	private double width;
	private double height;
	
	protected String name;
	
/*
 * ctor - initializes the rectangle to the specified width and height
 */
	public Rectangle(double width, double height, String name) {
		this.width = width;
		this.height = height;
		
		this.name = name;
	}

	/**
	 * @return the width
	 */
	public double getWidth() {
		return width;
	}

	/**
	 * @param width the width to set
	 */
	public void setWidth(double width) {
		this.width = width;
	}

	/**
	 * @return the height
	 */
	public double getHeight() {
		return height;
	}

	/**
	 * @param height the height to set
	 */
	public void setHeight(double height) {
		this.height = height;
	}

	/**
	 * computes the perimeter of this rectangle
	 * @return the perimeter 
	 */
	public double computePerimeter() {
		return 2*width + 2*height;
	}
	
	/**
	 * computes the area of this rectangle
	 * @return the area 
	 */
	public double computeArea() {
		return width * height;
	}
	
	/**
	 * Create a String representation of this object
	 */
	public String toString() {
		String s = String.format("Rectangle %s: width=%#.2f, height=%#.2f, area=%#.2f, perimeter=%#.2f", name, width, height, computeArea(), computePerimeter());
		return s;
	}
}



// This is the DriverApp class that tests the Rectangle and Square classes
public class DriverApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Rectangle r1 = new Rectangle( 3, 2, "r1");
		System.out.println(r1);
		
		Square s1 = new Square( 2.5, "s1");
		System.out.println(s1);
		
	}
}