Java Reference
In-Depth Information
Subclass rhombus
A rhombus is a parallelogram whose sides are all the same length. Note the
phrase “is a” in the previous sentence. A rhombus is a parallelogram. Therefore,
we make Rhombus a subclass of class Parallelogram . Its design appears in Fig.
4.12
Activity
4-4.3
The constructor for class Rhombus has as its parameters the four properties
that define a rhombus. We decide that we do not need to override inherited pro-
cedure drawShape . After all, a rhombus is a parallelogram, and the inherited pro-
cedure should work. However, we do override function toString because we
want toString to tell us what kind of shape the instance describes. For example,
toString could produce output like this:
"rhombus, pt (5, 20), side length 60, leaning factor 7 "
Class Rhombus is included just to make it a bit easier for clients. Instead of
creating a Parallelogram with the two side lengths equal, they can create a
Rhombus with only one side length.
Class Square
Finally, we design a class Square . A square is a rhombus in which each
angle is 90 degrees, i.e. has leaning factor 0. Since a square is a rhombus, we
make Square a subclass of Rhombus .
The constructor of Square is quite straightforward, as is method toString .
At this point, a bit of thinking about implementation creeps in. It is easy to
draw a square using Graphics procedure drawRect . Therefore, we override
inherited procedure drawShape so that we can have a simple implementation. Is
this a good idea? In this small design of shape-drawing classes, it does not real-
ly matter whether we override drawShape or not. We do it just to show the kind
of thinking that might go on in a design.
Activity
4-1.3
import java.awt.*;
/** A rhombus that can be drawn. */
public class Rhombus extends Parallelogram {
/** Constructor: a rhombus with side length l , bounding box with top-left corner
(x, y), and leaning factor d .
*/
public Rhombus( int x, int y, int l, int d) { }
// = description of this parallelogram
public String toString()
{ return ""; }
}
Figure 4.12:
The design of class Rhombus

Search WWH ::

Custom Search