Java Reference
In-Depth Information
draw shapes and perform other operations on them without knowing what they are — and of course poly-
morphism can help here.
You don't want to use the shape classes defined in java.awt.geom directly because you want to add
your own attributes such as color or line style for the shapes and store them as part of your shape objects.
You could consider using the shape classes as base classes for your shapes, but you couldn't use the Gen-
eralPath class in this scheme of things because, as I said earlier, the class has been defined as final and
therefore cannot be subclassed. You could define an interface that all your shape classes would implement.
However, some methods have a common implementation in all your shape classes, which would mean that
you would need to repeat this code in every class.
Taking all of this into account, the easiest approach might be to define a common base class for the
Sketcher shape classes and include a member in each class to store a java.awt.geom shape object of one
kind or another. You are then able to store a reference to any of your shape class objects as the base class
type and get polymorphic behavior.
You can start by defining a base class, Element , from which you derive the classes defining specific types
of shapes for Sketcher. The Element class has data members that are common to all your shape types, and
contains all the methods that you want to be able to execute polymorphically. Each shape class that is de-
rived from the Element class might need its own implementation of some or all of these methods.
Figure 19-22 shows the initial members that you define in the Element base class. The class is serial-
izable because you want to write a sketch to a file eventually. There are three fields: the color member
to store the color of a shape, the position member to store the location of a shape, and the serialVer-
sionUID member for serialization. The getBounds() method returns a rectangle that completely encloses
the element. This is for use in paint operations. The draw() method draws an element. The getBounds()
and draw() methods are abstract here because the Element class is not intended to define a shape. They
need to be included in the Element class to be able to call them polymorphically for derived class objects.
You can implement the getColor() and getPosition() methods in this class though.
FIGURE 19-22
 
 
Search WWH ::




Custom Search