Java Reference
In-Depth Information
public Point(Point point) {
x = point.x;
y = point.y;
}
// Convert a point to a string
public String toString() {
return x+","+y;
}
// Coordinates of the point
protected double x;
protected double y;
}
Both data members will be inherited in any subclass because they are specified as protected. They
are also insulated from interference from outside the package containing the class. The toString()
method will allow Point objects to be concatenated to a String object for automatic conversion - in
an argument passed to the println() method for example.
The next question you might ask is, "Should I derive the class PolyLine from the class Point ?" This has a
fairly obvious answer. A polyline is clearly not a kind of point, so it is not logical to derive the class
PolyLine from the Point class. This is an elementary demonstration of what is often referred to as the ' is a '
test. If you can say that one kind of object 'is a' specialized form of another kind of object, you may have a
good case for a derived class (but not always - there may be other reasons not to!). If not, you don't.
The complement to the 'is a' test is the ' has a ' test. If one object 'has a' component that is an object of another
class, you have a case for a class member. A House object 'has a' door, so a Door variable is likely to be a
member of the class House . Our PolyLine class will contain several points, which looks promising, but we
should look a little more closely at how we might store them, as there are some options.
Designing the PolyLine Class
With the knowledge we 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 a segment or two to an existing object. With an array storing the points, we will need to
create a new array each time we add a segment, then copy all the points from the old array to the new
one. This could be time consuming if we have a PolyLine object with a lot of segments.
We have another option. We 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 long as you
have a variable containing the first Point object, you can access all the points in the list, as shown in
the following diagram:
Search WWH ::




Custom Search