Java Reference
In-Depth Information
// Create a Point from an existing Point object
public Point(final Point aPoint) {
x = aPoint.x;
y = aPoint.y;
}
// Move a point
public void move(double xDelta, double yDelta) {
// Parameter values are increments to the current coordinates
x += xDelta;
y += yDelta;
}
// Calculate the distance to another point
public double distance(final Point aPoint) {
return 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"
}
// Coordinates of the point
private double x;
private double y;
}
Directory "Geometry"
The members have been resequenced within the class, with the private members appearing last. You
should maintain a consistent ordering of class members according to their access attributes, as it makes
the code easier to follow. The ordering adopted most frequently is for the most accessible members to
appear first and the least accessible last, but a consistent order is more important than the particular order
you choose.
How It Works
Now the instance variables x and y cannot be accessed or modified from outside the class, as they are
private. The only way these can be set or modified is through methods within the class, either with con-
structors or the move() method. If it is necessary to obtain the values of x and y from outside the class,
as it might well be in this case, a simple function does the trick. For example
public double getX() {
return x;
}
Couldn't be easier really, could it? This makes x freely available, but prevents modification of its value
from outside the class. In general, such methods are referred to as accessor methods and usually have
the form getXXX() . Methods that allow a private data member to be changed are called mutator methods
and are typically of the form setXXX() , where a new value is passed as an argument. For example:
Search WWH ::




Custom Search