Java Reference
In-Depth Information
aPoint.y));
}
// Convert a point to a string
public String toString() {
return Double.toString(x) + ", " + y;
// As "x, y"
}
Directory "Try Geometry"
You should save this as
Point.java
in the directory
Try Geometry
.
How It Works
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 you have two constructors. One creates a
Point
object from a coordinate pair
passed as arguments of type
double
, and the other creates a new
Point
object from an existing one.
Three methods are included in the class. You have the
move()
method, which moves a
Point
to another
position by adding an increment to each of the coordinates. You also have the
distance()
method,
which calculates the distance from the current
Point
object to the
Point
object passed as the argument.
This uses the Pythagorean theorem to compute the distance, as shown in
Figure 5-7
.
Finally, you have a
toString()
method, which returns a string representation of the coordinates of the
current point. If a class defines the
toString()
method and an object of that class is used as an operand
of the string concatenation operator
+
, the method is called to represent the object as a string. The com-
piler automatically inserts a call to
toString()
when necessary. For example, suppose
thePoint
is an
object of type
Point
, and you write the statement:
System.out.println("The point is at " + thePoint);
The
toString()
method is automatically invoked to convert the object referenced by the variable
thePoint
to a
String
, and the resultant string is appended to the
String
literal. You have specified the
toString()
method as
public
, as this is essential here for the class to compile. I will defer explanations
as to why this is necessary until a little later in this chapter.