Java Reference
In-Depth Information
Point end = new Point(5.0, 6.0);
System.out.println("Points created are " + start + " and " + end);
// Create two lines and display them
Line line1 = new Line(start, end);
Line line2 = new Line(0.0, 3.0, 3.0, 0.0);
System.out.println("Lines created are " + line1 + " and " + line2);
// Display the intersection
System.out.println("Intersection is " + line2.intersects(line1));
// Now move the end point of line1 and show the new intersection
end.move(1.0, -5.0);
System.out.println("Intersection is " + line1.intersects(line2));
}
}
The program will produce the output:
Points created are 0.0, 1.0 and 5.0, 6.0
Lines created are (0.0, 1.0):(5.0, 6.0) and (0.0, 3.0):(3.0, 0.0)
Intersection is 1.0, 2.0
Intersection is 1.0, 2.0
How It Works
We first create two Point objects, which we will use later in the creation of the object line1 . We then
display the points using the println() method. The toString() method that we defined in the
Point class is used automatically to generate the String representation for each Point object.
After creating line1 from our two points, we use the other constructor in the Line class to create
line2 from two pairs of coordinates. We then display the two lines. The toString() member of the
Line class is invoked here to create the String representation of each Line object, and this in turn
uses the toString() method in the Point class.
The next statement calls the intersects() method from the line2 object and returns the Point
object at the intersection of the two lines, line1 and line2 , as part of the argument to the
println() method that outputs the point. As you see, we are not obliged to save an object when we
create it. Here we just use it to create the string to be displayed.
We use the move() method in the class Point to modify the coordinates of the object, end , that we
used to create line1 . We then get the intersection of the two lines again, this time calling the
intersects() method from line1 . The output result demonstrates that line1 is independent of the
object end , as moving the point has made no difference to the intersection .
If you change the constructor in the Line class, to the version we saw earlier that does not create new
Point objects to define the line, you can run the example again to see the effect. The output will be:
Points created are 0.0, 1.0 and 5.0, 6.0
Lines created are (0.0, 1.0):(5.0, 6.0) and (0.0, 3.0):(3.0, 0.0)
Intersection is 1.0, 2.0
Intersection is 2.0, 1.0
Search WWH ::




Custom Search