ShapeApp is the application. First, it prints out the HTML header information. Then it performs 8 basic operations and prints out information after each operation.
Shape is an abstract class that defines the fields, methods, and behavior that will be common to all shapes. In particular, all shapes will have an x and y location, a width and height, and a color. All shapes will have the following methods: moveTo(), draw(), area(), and perimeter(). Shape includes a constructor which is used to initialize a shape. Since moving only requires changing the x and y coordinates of a shape, that method can be defined in the Shape class itself. On the other hand, drawing and computing areas and perimeters requires specific knowledge about the kind of shape, so these methods are declared "abstract" and their implementation is deferred to the subclasses.
myRectangle and myEllipse extend the class shape and provide specific methods for drawing, and for computing the area and perimeter. The constructors use the constructor of their superclass through the "super" keyword. The moveTo() method is inherited without change from the superclass, Shape. On the other hand, the draw(), area(), and perimeter() methods are overridden to provide the proper behavior. The toString() method adds the classname of the object to the general information returned by the superclass method.
mySquare extends the rectangle class. It simply adds new constructors to insure that it is a "square" rectangle. It also has a toString method that adjusts the result from the rectangle method.
Steps 4 and 8 illustrate that the fields of the shape objects are accessible outside the class and can be changed. In step 4 this doesn't appear to be a problem, but step 8 shows that accessible fields can lead to serious problems. In this case we can't insure that some outside part of the program won't destroy the squareness of our square. The next example will show how to protect fields from outside intervention.
The application, ShapeApp.class, is actually run on the math server when you request the page, and it prints out both the results and the html tags for dispaying the page. ShapeApp.cgi is a small shell file which actually runs the java application. Here is the text of ShapeApp.cgi.
This cgi interface is very dependent on the server you are running. This example is running on an Apache server in the Department of Mathematical Sciences.#!/usr/bin/csh setenv CLASSPATH . setenv JAVA_HOME /usr/local/java setenv LD_LIBRARY_PATH /usr/local/java/lib:/usr/local/lib /usr/local/java/bin/java ShapeApp
The fields in Shape are declared protected, which means that they can only be accessed by classes in the same package or subclasses. Methods for retrieving and adjusting the field values then have to be added. However, this makes it possible to override the setWidth() and setHeigth() methods in the case of a square so that the constraint of "squareness" is never violated.