01 // ShapeFactory.java
02
03 import
java.util.Vector;
04 import java.util.Enumeration;
05
06 public class ShapeFactory
07 {
08 public static void main(String[] args)
09 {
10 Vector vGeoObj = new
Vector();
11
GeometricObject obj;
12
13
// vGeoObj.add(new GeometricObject());
14 vGeoObj.add(new
Rectangle());
15
vGeoObj.add(new Rectangle(1, 2, 3));
16 vGeoObj.add(new
Square(1, 2, 3));
17 vGeoObj.add(new
Rectangle(-1, -2, -3, -4));
18
19
System.out.println("Total number of GeometricObjects created is " +
GeometricObject.count + ".");
20
21 for(int i=0;
i<vGeoObj.size(); i++)
22 {
23
obj = (GeometricObject)vGeoObj.elementAt(i);
24
System.out.println("The area of GeometricObject[" + i + "] is: " + obj.getArea()
+ ".");
25 }
26 }
27 }
01 // GeometricObject.java
02
03 public
abstract class GeometricObject extends Object {
04 private
static int count = 0;
05
06 public
GeometricObject()
07 {
08 ++count; // increment static count of
GeometricObjects
09 System.out.println(
"Current count of GeometricObjects is " + count );
10 }
11
12 public static int getCount() { return count;
}
13 public abstract double getArea();
14 }
01 // Rectangle.java
02
03 public class
Rectangle extends GeometricObject {
04 private double x0, y0,
xlen, ylen;
05
06 public Rectangle()
07 {
08 x0 = 0.0;
09 y0 = 0.0;
10 xlen = 1.0;
11 ylen = 1.0;
12 }
13
14 public Rectangle( double x0_, double y0_,
double len_ ) throws Exception
15 {
16 if (len_ <= 0) throw new
Exception("Non-positive length exception.");
17 x0 = x0_;
18 y0 = y0_;
19 xlen = len_;
20 ylen = len_;
21 }
22
23 public Rectangle( double x0_, double y0_,
double xlen_, double ylen_ ) throws Exception
24 {
25 if (xlen_ <= 0 || ylen_ <= 0) throw new
Exception("Non-positive length exception.");
26 x0 = x0_;
27 y0 = y0_;
28 xlen = xlen_;
29 ylen = ylen_;
30 }
31
32 public double getx0() { return x0; }
33 public double gety0() { return y0; }
34
public double getArea() { return xlen*ylen; }
35 }
01 // Square.java
02
03 public class Square
extends Rectangle {
04
05 public Square()
06 {
07 super();
08 }
09
10 public Square(double x0, double y0, double
length) throws Exception
11 {
12 super(x0, y0, length);
13 }
14 }