Java Reference
In-Depth Information
// Calculate the length of a line
double length() {
return start.distance(end); // Use the method from the Point class
}
// Convert a line to a string
public String toString() {
return "(" + start+ "):(" + end + ")"; // As "(start):(end)"
} // that is, "(x1, y1):(x2, y2)"
}
You should save this as
Line.java
in the directory
TryGeometry
.
How It Works
You shouldn't have any difficulty with this class definition, as it is very straightforward. The class
Line
stores two
Point
objects as instance variables. There are two constructors for
Line
objects, one
accepting two
Point
objects as arguments, the other accepting the (x, y) coordinates of the start and
end points. You can see how we use the variable
this
to differentiate the class instance variables,
start
and
end
, from the parameter names in the constructor.
Note how the constructor that accepts
Point
objects works:
// Create a line from two points
Line(final Point start, final Point end) {
this.start = new Point(start);
this.end = new Point(end);
}
With this implementation of the constructor, two new
Point
objects are created which will be identical
to, but independent of, the objects passed to the constructor. If you don't think about what happens you
might be tempted to write it as:
// Create a line from two points
Line(final Point start, final Point end) {
this.start = start; // Dependent on external object!!!
this.end = end; // Dependent on external object!!!
}
The important thing you should notice here, is that the way the constructor is implemented could cause
problems that might be hard to track down. It's the same problem of an object variable being separate
from the object to which it refers. In this version of the constructor no new points are created. The
start
and
end
members of the object refer to the
Point
objects passed as arguments. The
Line
object will be implicitly dependent on the
Point
objects that are used to define it. If these were
changed outside the
Line
class, by using the
move()
method for example, this would 'silently' modify
the
Line
object. You might consciously decide that this is what you want, so the
Line
object continues
to be dependent on its associated
Point
objects, for instance in a drawing package. But, in general, you
should avoid implicit dependencies between objects.