Java Reference
In-Depth Information
Try It Out - Calculating the Intersection of Two Lines
We can use these results to write the additional method we need for the
Line
class. Add the following
code to the definition in
Line.java
:
// Return a point as the intersection of two lines -- called from a Line object
Point intersects(final Line line1) {
Point localPoint = new Point(0, 0);
double num = (this.end.y - this.start.y)*(this.start.x - line1.start.x) -
(this.end.x - this.start.x)*(this.start.y - line1.start.y);
double denom = (this.end.y - this.start.y)*(line1.end.x - line1.start.x) -
(this.end.x - this.start.x)*(line1.end.y - line1.start.y);
localPoint.x = line1.start.x + (line1.end.x - line1.start.x)*num/denom;
localPoint.y = line1.start.y + (line1.end.y - line1.start.y)*num/denom;
return localPoint;
}
Since the
Line
class definition refers to the
Point
class, the
Line
class can't be compiled without the
other being available. When you compile the
Line
class the compiler will compile the other class too.
How It Works
The
intersects()
method is called from one
Line
object, and takes another
Line
object as an argument.
In the code, the local variables
num
and
denom
are the numerator and denominator in the expression for
t
in the diagram. We then use these values to calculate the
x
and
y
coordinates for the intersection.
If the lines are parallel, the denominator in the equation for
t
will be zero, something
you should really check for in the code. For the moment, we will ignore it and end up
with coordinates that are
Infinity
if it occurs.
Note how we get at the values of the coordinates for the
Point
objects defining the lines. The dot
notation for referring to a member of an object is just repeated when you want to reference a member of
a member. For example, for the object
line1
, the expression
line1.start
refers to the
Point
object at the beginning of the line. Therefore
line1.start.x
refers to its x coordinate, and
line1.start.y
accesses its y coordinate.
Now we have a
Line
class, which we can use to calculate the intersection point of two
Line
objects.
We need a program to test the code out.
Try It Out - The TryGeometry Class
We can demonstrate the two classes we have defined, with the following code in the method
main()
:
public class TryGeometry {
public static void main(String[] args) {
// Create two points and display them
Point start = new Point(0.0, 1.0);