The Shape Hierarchy Example

public abstract class Shape
{
   String name;
   double area;
   public void display()
     {
        System.out.println("Object type: " + name);
        System.out.println("Object area: " + area);
     }
}
The base class of the Shape hierarchy. Every object that we want to consider is a geometric shape. All geometric shapes have in common that they have a name (Rectangle, Triangle, etc) and an area.   

Also, all geometric shapes need a method to print out information about themselves.  

public class Circle extends Shape
{
   private double  radius;
   public Circle(double _radius)
     {
        name = "Circle";
        radius = _radius;
     }
   public void computeArea()
     {
        area = Math.PI * radius * radius;
     }
}
Our first example of a Shape is a Circle. Since a Circle is a Shape, we specify that a Circle extends Shape  

A Circle, specifically, always must have a radius  

A Circle has a particular way to compute its area if the radius is known  

public class Rectangle extends Shape
{ 
   private double height, width;
   public Rectangle(double _height, double _width)
     {
        name = "Rectangle";
        height = _height;
        width = _width;
     }
   public void computeArea()
     {
        area = height * width;
     }
   public void display()
     {
        super.display();
        System.out.println("Dimension: "+height+" x "+width);
     }
}
Our second example of a Shape is a Rectangle. Since a Rectangle is a Shape, we specify that Rectangle extends Shape  

A Retangle, specifically, always has a height and a width  

A Rectangle has a specific way to compute its area, given the height and width  

A Retangle does inherit the 'general' display method, but we want to print out more information.  

public class Square extends Rectangle
{
   public Square(double _side)
     {
        super(_side, _side);
        name = "Square";
     }
}
Our last example of a Shape is a Square. A Square is a Shape, but it is also a particular type of Rectangle.  

To construct a Square is really the same as constructing a Rectangle where the width and height are the same.  

public class ShapeTest
{ 
   public static void main(String args[])
     {
        Rectangle r = new Rectangle(2, 4);
        Square    s = new Square(5);
        Circle    c = new Circle(1);
        
        r.computeArea(); s.computeArea(); c.computeArea();
        r.display();     s.display();     c.display();
     }
}
Since we do want to check if everything is working, we create a test class that should be "runnable"  

Then we need to create some instances of a Rectangle, Circle, and Square  
Finally, we want to test if the objects work correctly