Java Reference
In-Depth Information
In the
toString()
method for the
Line
class, we are able to use the
Point
objects directly in the
formation of the
String
representation of a
Line
object. This works because the
Point
class also
defines a
toString()
method.
We've now defined two classes. In these class definitions, we've included the basic data that defines an
object of each class. We've also defined some methods which we think will be useful, and added
constructors for a variety of input parameters. Note how the
Point
class is used in the definition of the
Line
class. It is quite natural to define a line in terms of two
Point
objects, and the
Line
class is much
simpler and more understandable than if it was defined entirely in terms of the individual x and y
coordinates. To further demonstrate how classes can interact, and how you can solve problems directly,
in terms of the objects involved, let's devise a method to calculate the intersection of two
Line
objects.
Creating a Point from Two Lines
We could add this method to the
Line
class. The diagram below illustrates how the mathematics works out.
x = x +(x -x )s
y = y +(y -y )s
3 4 3
343
x,
11
x,
44
line1
x = x +(x -x )t
y = y +(y -y )t
121
121
line2
x,
33
x,
22
X-Axis
At the intersection point:
x +(x -x )s = x +(x -x )t
y +(y -y )s = y +(y -y )t
You can calculate x,y for the
intersection by substituting t
back in the equations for
343
121
343
121
line 1
.
from which you get:
t =
(y -y )(x -x ) - (y -y )(x -x )
(y -y )(x -x ) - (y -y )(x -x )
43 31
31 43
43 21
21 43
You can ignore the mathematics if you want to, as it is not the most important aspect of the example. If
you are willing to take the code in the new constructor on trust, then skip to the
Try It Out
section
below. On the other hand you shouldn't find it too difficult if you can still remember what you did in
high school.
One way to get the intersection of two lines is to use equations like those shown. These are called
parametric equations because they use a parameter value (
s
or
t
) as the variable for determining points
on each line. The parameters
s
and
t
vary between 0 and 1 to give points on the lines between the
defined start and end points. When a parameter
s
or
t
is 0 the equations give the coordinates of the start
point of each line, and when the parameter value is 1 you get the end point of the line.
Where the lines intersect, the equations for the lines must produce the same (x, y) values, so, at this
point, the right-hand sides of the equations for x for the two lines must be equal, and the same goes
for the equations for y. This will give you two equations in
s
and
t
, and with a bit of algebraic
juggling you can eliminate
s
to get the equation shown for
t
. You can then replace
t
in the
equations defining
line 1
to get
x
and
y
for the intersection point.