Computer Science 121
Example illustrating polymorphism

import java.awt.*;
import java.applet.Applet;

public class ShapesApplet extends Applet
{
    private Shape s;
    private Circle c;
    private Rectangle r;

    public void init ()
    {
        s = new Shape (Color.blue, 50, 100);
        c = new Circle (Color.red,100, 100, 30);
        r = new Rectangle (Color.green, 200, 100, 60, 40);
    } // method init

    public void paint (Graphics g)
    {
        s.drawShape (g);
        s = c;
        s.drawShape (g);
        s = r;
        s.drawShape (g);
    } // method paint
} // class ShapesApplet

class Shape
{
    protected Color color;
    protected int x, y;

    Shape (Color c, int xPosition, int yPosition)
    {
        color = c;
        x = xPosition;
        y = yPosition;
    } // constructor

    public void drawShape (Graphics g)
    {
        g.setColor (color);
        g.drawString ("Shape", x, y);
    } // method drawShape
} // class Shape

class Circle extends Shape
{
    private int radius;

    Circle (Color c, int x, int y, int r)
    {
        super (c, x, y);
        radius = r;
    } // constructor

    public void drawShape (Graphics g)
    {
        g.setColor (color);
        g.fillOval (x, y, 2*radius, 2*radius);
    } // method drawShape
} // class Circle

class Rectangle extends Shape
{
    private int width, height;

    Rectangle (Color c, int x, int y, int w, int h)
    {
        super (c, x, y);
        width = w;
        height = h;
    } // constructor

    public void drawShape (Graphics g)
    {
        g.setColor (color);
        g.fillRect (x, y, width, height);
    } // method drawShape
} // class Rectangle