Programming Drill #16

Due: Tuesday, June 17
Goal:  Learn what inheritance can do for you

Here are the definitions for a Shape class and a Circle class that is derived from Shape.  In this example, inheritance lets us inherit the name variable so we don't have to redefine it.

public class Shape
{
	private String name;

	public Shape()
	{
		name = "Unknown";
	}

	public Shape(String name)
	{
		this.name = name;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String newName)
	{
		this.name = newName;
	}

	// You should override this
	public double getArea()
	{
		return 0;
	}
}


public class Circle extends Shape
{
	private int radius;

	public Circle()
	{
		super("Circle");
		radius = 0;
	}

	public Circle(int radius)
	{
		super("Circle");
		this.radius = radius;
	}

	public void setRadius(int newRadius)
	{
		this.radius = newRadius;
	}

	public int getRadius()
	{
		return radius;
	}

	public double getArea()
	{
		return Math.PI * radius * radius;
	}
}
    

Put these classes into appropriate .java files.  Add another class, Rectangle, that also extends the Shape class.  Modify the Rectangle class appropriately so it has a private width and height instance variables, a constructor that allows the user to set the width and height, accessors to retrieve the width and height, and an appropriately defined getArea method that calculates the area of the rectangle.

Add the following code into the main method:

		Circle c = new Circle(2);
		System.out.println(c.getName() +
					" has radius " + c.getRadius() +
					" and area " + c.getArea());

		Rectangle r = new Rectangle(3,4);
		System.out.println(r.getName() +
					" has width " + r.getWidth() +
					" has height " + r.getHeight() +
					" and area " + r.getArea());
    

The program should output:

Circle has radius 2 and area 12.566370614359172
Rectangle has width 3 has height 4 and area 12.0