Java Reference
In-Depth Information
x 2
x, 22
y- 21
x 1
-
x 21
x, 11
X-Axis
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:
return String.valueOf(x) + ", " + y; // As "x, y"
Try It Out - The Line Class
We can use Point objects in the definition of the class Line :
class Line {
Point start; // Start point of line
Point end; // End point of line
// Create a line from two points
Line(final Point start, final Point end) {
this.start = new Point(start);
this.end = new Point(end);
}
// Create a line from two coordinate pairs
Line(double xStart, double yStart, double xEnd, double yEnd) {
start = new Point(xStart, yStart); // Create the start point
end = new Point(xEnd, yEnd); // Create the end point
}
Search WWH ::




Custom Search