Java Reference
In-Depth Information
Note how you use the static toString( ) method defined in the Double class to convert the x value to a
String . The compiler inserts a call to the same method automatically for the y value, as the left operand
of the + operation is a String object. Note that you 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
You 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
}
// Calculate the length of a line
double length() {
return start.distance(end);
// Use the method from the
Point class
}
// Convert a line to a string
public String toString() {
return "(" + start+ "):(" + end + ")"; // As "(start):(end)"
}
// that is, "(x1,
y1):(x2, y2)"
Directory "Try Geometry"
You should save this as the file Line.java in the Try Geometry directory.
Search WWH ::




Custom Search