{ |one, step, back| }

The Shape Example in Java

Contributed by Jim Weirich

Code for Java

File: Shape.java

interface Shape
{
    public void Draw ();
    public void MoveTo (int newx, int newy);
    public void RMoveTo (int dx, int dy);
}

File: Rectangle.java

class Rectangle
    implements Shape
{
    public Rectangle (int initx, int inity, int initw, int inith)
    {
	x = initx;
	y = inity;
	width = initw;
	height = inith;
    }
    
    public void Draw ()
    {
	System.out.println (
	    "Drawing a Rectangle at (" + x + "," + y
	    + "), width " + width + ", height " + height);
    };

    public void MoveTo (int newx, int newy)
    {
	x = newx;
	y = newy;
    }

    public void RMoveTo (int dx, int dy)
    {
	x += dx;
	y += dy;
    }

    public void SetWidth (int newWidth)
    {
	width = newWidth;
    }

    public void SetHeight (int newHeight)
    {
	height = newHeight;
    }

    private int x;
    private int y;
    private int width;
    private int height;
};

File: Circle.java

class Circle
    implements Shape
{
    public Circle (int initx, int inity, int initradius)
    {
	x = initx;
	y = inity;
	radius = initradius;
    }
    
    public void Draw ()
    {
	System.out.println (
	    "Drawing a Circle at (" + x + "," + y
	    + "), radius " + radius);
    };

    public void MoveTo (int newx, int newy)
    {
	x = newx;
	y = newy;
    }

    public void RMoveTo (int dx, int dy)
    {
	x += dx;
	y += dy;
    }

    public void SetRadius (int newRadius)
    {
	radius = newRadius;
    }

    private int x;
    private int y;
    private int radius;
}

File: TryShape.java

class TryShape
{
    public static void DoSomethingWithShape (Shape s)
    {
	s.Draw ();
	s.RMoveTo (100, 100);
	s.Draw ();
    }

    public static void main (String argv[])
    {
    
	/* using shapes polymorphically */
	
	Shape shapes[] = new Shape[2];
	shapes[0] = new Rectangle (10, 20, 5, 6);
	shapes[1] = new Circle (15, 25, 8);
	
	for (int i=0; i<2; ++i) {
	    DoSomethingWithShape (shapes[i]);
	}
	
	/* access a rectangle specific function */
	
	Rectangle rect = new Rectangle (0, 0, 15, 15);
	rect.SetWidth (30);
	rect.Draw ();
    }
}

Output

Drawing a Rectangle at (10,20), width 5, height 6
Drawing a Rectangle at (110,120), width 5, height 6
Drawing a Circle at (15,25), radius 8
Drawing a Circle at (115,125), radius 8
Drawing a Rectangle at (0,0), width 30, height 15