Java Reference
In-Depth Information
Try It Out - The Point Class
We first define a basic class for point objects:
class Point {
// Coordinates of the point
double x;
double y;
// Create a point from coordinates
Point(double xVal, double yVal) {
x = xVal;
y = yVal;
}
// Create a point from another Point object
Point(final Point oldPoint) {
x = oldPoint.x; // Copy x coordinate
y = oldPoint.y; // Copy y coordinate
}
// Move a point
void move(double xDelta, double yDelta) {
// Parameter values are increments to the current coordinates
x += xDelta;
y += yDelta;
}
// Calculate the distance to another point
double distance(final Point aPoint) {
return Math.sqrt(
(x - aPoint.x)*(x - aPoint.x) + (y - aPoint.y)*(y - aPoint.y) );
}
// Convert a point to a string
public String toString() {
return Double.toString(x) + ", " + y; // As "x, y"
}
}
You should save this as
Point.java
in the directory
TryGeometry
.
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 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.