Java Reference
In-Depth Information
It seems reasonable to represent points as objects of a class Point . Points are well-defined objects that
occur in the context of all kinds of geometric entities. You have seen a class for points earlier, which you
put in the Geometry package. Rather than repeat the whole class, let's just define the bare bones of what you
need in this context:
public class Point {
// Create a point from its coordinates
public Point(double xVal, double yVal) {
x = xVal;
y = yVal;
}
// Create a point from another point
public Point(Point point) {
x = point.x;
y = point.y;
}
// Convert a point to a string
@Override
public String toString() {
return x+","+y;
}
// Coordinates of the point
protected double x;
protected double y;
}
Directory "TryPolyLine"
Save the source file containing this code in a new directory, TryPolyLine . You add all the files for the
example to this directory. Both data members of Point are inherited in any subclass because they are speci-
fied as protected. They are also insulated from interference from outside the package containing the class.
The toString() method enables Point objects to be concatenated to a String object for automatic con-
version — 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 isa test is the hasa test. If one object hasa component that is an object of another
class, you have a case for a class member. A House object has a door, so a variable of type Door is likely
to be a member of the class House . The PolyLine class contains several points, which looks promising, but
you should look a little more closely at how you might store them, as there are some options.
Search WWH ::




Custom Search