// An example to illustrate polymorphism.
public class Shapes extends Applet
{
private Shape shape;
private Circle circle;
private Rectangle rectangle;
public void init ()
{
circle = new Circle (Color.red,100,
100, 30);
rectangle = new Rectangle
(Color.green, 200, 100, 60, 40);
} // method init
public void paint (Graphics g)
{
shape = circle;
shape.drawShape (g);
shape = rectangle;
shape.drawShape (g);
} // method paint
} // public class Shapes extends Applet
abstract class Shape
{
protected Color color;
protected int x, y;
Shape (Color c, int xVal, int yVal)
{
color = c;
x = xVal;
y = yVal;
} // method shape
abstract public void drawShape (Graphics g);
} // class Shape
class Circle extends Shape
{
private int radius;
Circle (Color c, int x, int y, int r)
{
super (c, x, y);
radius = r;
} // method Circle
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;
} // method Rectangle
public void drawShape (Graphics g)
{
g.setColor (color);
g.fillRect (x, y, width,
height);
} // method drawShape
} // class Rectangle