Beginning Java 2 SDK 1.4 Edition

Using Objects

[The following is a continuation of our series of excerpts from
chapter 5 of the Wrox Press title,
Beginning Java 2 SDK 1.4 Edition. Source code for the examples discussed can
be downloaded at the Wrox Web site (free
e-mail registration required).]

Let's create an example to do some simple 2D geometry. This will give us an opportunity to use
more than one class. We will define two classes, a class of point objects and a class of line
objects--we then use these to find the point at which the lines intersect. We will call the example
TryGeometry, so this will be the name of the directory or folder in which you should save
the program files. Quite a few lines of code are involved so we will put it together piecemeal,
and try to understand how each piece works as we go.

This is a simple class that has just two instance variables, x and y, which
are the coordinates of the Point object. At the moment we have two constructors. One
will create a point from a coordinate pair passed as arguments, and the other will create a new
Point object from an existing one.

There are three methods included in the class. First we have the move() method that
moves a Point to another position by adding an increment to each of the coordinates.
We also have the distance() method that calculates the distance from the current
Point object to the Point object passed as an argument. This uses the
Pythagorean theorem to compute the distance as shown below.

Finally we have a method toString() that returns a string representation of the
coordinates of the current point. If a class defines the toString() method, an object of
that class can be used as an operand of the string concatenation operator +, so you can implement
this in any of your classes to allow objects to be used in this way. The compiler will automatically
insert a call to toString() when necessary. For example, suppose thePoint is
an object of type Point, and we write the statement:

System.out.println("The point is at " + thePoint);

The toString() method will be automatically invoked to convert thePoint to
a String, and the result will be appended to the String literal. We have
specified the toString() method as public, as this is essential here for the class to
compile. We will defer explanations as to why this is so until later in this chapter.

Note how we use the static toString() method defined in the class Double
to convert the x value to a String. The compiler will insert a call to the
same method automatically for the y value as the left operand of the +
operation is a String object. Note that we could equally well have used the
valueOf() method in the String class. In this case the statement would be
written like this: