import java.awt.*;
import java.applet.Applet;
// This applet uses polymorphism to decide which shape
to draw. If shape is instantiated as a new
// Circle, it draws a circle, but if it is instantiated
as a new Square, it draws a square.
public class Figures extends Applet
{
private Shape shape; // shape is an
instance variable whose type is an interface.
public void paint (Graphics g)
{
shape = new
Circle (Color.red, 100, 100);
shape.drawShape
(g);
shape.drawAreaString
(g);
shape = new
Square (Color.green, 100, 200);
shape.drawShape
(g);
shape.drawAreaString
(g);
} // method paint
} // class Figures
// This interface defines the public methods in the classes
that implement it.
interface Shape
{
public void drawShape (Graphics g);
public void drawAreaString (Graphics
g);
} // interface Shape
class Circle implements Shape
{
private Color color;
private int x, y, diameter;
Circle (Color c, int xPosition, int
yPosition)
{
color = c;
x = xPosition;
y = yPosition;
diameter =
50;
} // constructor
public void drawShape (Graphics g)
{
g.setColor
(color);
g.fillOval
(x, y, diameter, diameter);
} // method drawShape
private int calculateArea ()
{
int area,
radius = diameter / 2;
area = (int)(Math.PI
* radius * radius);
return area;
} // method calculateArea
public void drawAreaString (Graphics
g)
{
g.setColor
(Color.black);
int area =
calculateArea ();
g.drawString
("Area of Circle: "+ area, 100, 75);
} // method drawAreaString
} // class Circle
class Square implements Shape
{
private Color color;
private int x, y, side;
Square (Color c, int xPosition, int
yPosition)
{
color = c;
x = xPosition;
y = yPosition;
side = 50;
} // constructor
public void drawShape (Graphics g)
{
g.setColor
(color);
g.fillRect
(x, y, side, side);
} // method drawShape
private int calculateArea ()
{
int area;
area = side
* side;
return area;
} // method calculateArea
public void drawAreaString (Graphics
g)
{
g.setColor
(Color.black);
int area =
calculateArea ();
g.drawString
("Area of Square: "+area, 100, 275);
} // method drawAreaString
}// class Square