Java Reference
In-Depth Information
TRY IT OUT: The TryGeometry Class
You can exercise the two classes you 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);
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));
}
Directory "Try Geometry"
Save the
TryGeometry.java
file in the
Try Geometry
directory along with the other two class files,
Point.java
and
Line.jav
a. The program produces the following 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
You first create two
Point
objects, which you use later in the program to create the object
line1
. You
then display the points using the
println()
method. The
toString()
method that you defined in the
Point
class is used automatically to generate the
String
representation for each
Point
object.
After creating
line1
from the two points, you use the other constructor in the
Line
class to create
line2
from two pairs of coordinates. You 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 calls the
toString()
method in the
Point
class.