Java Reference
In-Depth Information
Designing the PolyLine Class
With the knowledge you have of Java, an array of Point objects looks like a good candidate to be a member
of the class. There are disadvantages, though. A common requirement with polylines is to be able to add
segments to an existing object. With an array storing the points you need to create a new array each time you
add a segment, then copy all the points from the old array to the new one. This could be time-consuming if
you have a PolyLine object with a lot of segments.
You have another option. You could create a linked list of points. In its simplest form, a linked list of
objects is an arrangement where each object in the list has a reference to the next object as a data member.
As long as you have a variable containing a reference to the first Point object, you can access all the points
in the list, as shown in Figure 6-7 .
FIGURE 6-7
Figure 6-7 illustrates the basic structure you might have for a linked list of points stored as a PolyLine .
The points are stored as members of ListPoint objects. In addition to constructors, the PolyLine class
needs a method to add points, but before you look into that, let's consider the ListPoint class in more
detail.
You could take one of at least three approaches to define the ListPoint class, and you could make argu-
ments in favor of all three.
• You could define the ListPoint class with the x and y coordinates stored explicitly. The main
argument against this would be that you have already encapsulated the properties of a point in the
Point class, so why not use it?
• You could regard a ListPoint object as something that contains a reference to a Point object,
plus members that refer to following ListPoint objects in the list. This is not an unreasonable
approach. It is easy to implement and not inconsistent with an intuitive idea of a ListPoint .
• You could view a ListPoint object as a specialized kind of Point , so you would derive the
ListPoint class from Point . Whether or not this is reasonable depends on whether you see this
as valid. To my mind, this is stretching the usual notion of a point somewhat — I would not use
this.
The best option looks to me to be the second approach. You could implement the ListPoint class with
a data member of type Point , which defines a basic point with its coordinates. A ListPoint object would
have an extra data member, next , of type ListPoint that is intended to contain a reference to the next ob-
ject in the list. With this arrangement, you can find all the points in a Polyline object by starting with its
start member, which stores a reference to its first ListPoint object. This contains a reference to the next
 
 
Search WWH ::




Custom Search