Java Reference
In-Depth Information
Example of object-oriented design
We design classes that facilitate drawing various shapes in a graphics window —
parallelograms, rhombuses, squares, etc. Later, you can augment these with
classes to draw triangles, right triangles, and other shapes of your choosing.
Get the classes
in this design
from a footnote
on lesson page
Class Shape
Class Shape will be the superclass of all shape classes —see Fig. 4.9. A
basic property of any shape is its placement in a graphics window, and its place-
ment is determined by the coordinates of the upper left corner of a bounding rec-
tangle for the shape. The constructor has these two values as parameters, and we
provide getter methods for them. We also have method toString , which may be
useful when debugging programs that create and use shapes.
The only other method is drawShape . This method should never be called,
since instances of Shape contain not shapes but only positions of shapes! As we
will see, it is included only so that it can be overridden in subclasses.
In the design of Fig. 4.9, we have written the function bodies with return
statements that return the default value for the return type. This is so that this
class definition is syntactically legal and will compile.
import java.awt.*;
/** A shape at an (x, y) coordinate. */
public class Shape {
/** Constructor: a shape that fits in a bounding rectangle with upper-left corner (x, y) */
public Shape( int x, int y){}
/** = x-coordinate of the upper-left corner of the bounding rectangle */
public int getX()
{ return 0; }
/** = y-coordinate of upper-left corner of the bounding rectangle */
public int getY()
{ return 0; }
/** = a description of this Shape , of the form ( x-coordinate , y-coordinate ) */
public String toString()
{ return ""; }
/** draw this shape using Graphics g --not to be called */
public void drawShape(Graphics g) {}
Figure 4.9:
The design of class Shape
Search WWH ::

Custom Search