Java Reference
In-Depth Information
Discussion
We designed four classes that create shapes in a graphics window. They
form a chain, moving from the abstract, in which no shape but only a position is
described, down to more and more restrictive shapes. This is the nature of the
object-oriented approach. As one proceeds down a hierarchy of classes, one
encounters more and more properties and restrictions.
We could design other shape classes. For example, a rectangle is a parallel-
ogram in which the angles are equal ( 90 degrees), so we could have a subclass
Rectangle of Parallelogram . That brings up a question: A square is a rectan-
gle whose sides are equal, and a square is a rhombus whose angles are equal;
should class Square be a subclass of Rectangle or of Rhombus ? It cannot be
both because “multiple inheritance” —inheriting from two difference super-
classes— is not allowed in Java. This is a situation where the subclassing feature
of Java cannot be made to model the problem domain exactly.
Java does have another feature, the interface , which could be used to model
the situation with rectangle, rhombus, and square more exactly. See Chap. 12.
The actual implementation of these classes is straightforward, and we leave
them to you. Also, the implementation can be found on the CD ProgramLive .
Using the shape classes
Activity 4-4.4 of the CD discusses a Java program that uses the shape class-
es to draw a figure like the one shown to the left. The design of the figure was
done with pencil and paper, away from the computer. We drew the figure and
determined what variables were needed and what they would represent.
Attempting to design the figure while on the computer would be inefficient.
The presence of the shape classes makes this figure fairly easy to draw —
imagine trying to draw it using only the original methods of class Graphics . And
yet, the classes themselves are quite short and simple. A good design will lead to
a simple, clear structure and a relatively simple program that is easy to use.
import java.awt.*;
/** A square that can be drawn */
public class Square extends Rhombus {
/** Constructor: a square with side length l and top-left corner (x, y) */
public Square( int x, int y, int l) { }
/** draw this square using Graphics g */
public void drawShape(Graphics g) { }
/** = a description of this square */
public String toString()
{ return ""; }
}
Figure 4.13:
The design of class Square
Search WWH ::




Custom Search