Java Reference
In-Depth Information
// 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 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"
}
// Coordinates of the point
private double x;
private double y;
}
The members have been re-sequenced 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
constructors, 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 would do 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:
public void setX(double inputX) {
x = inputX;
}
It may seem odd to use a method to alter the value of a
private
data member when you could just
make it
public
. The main advantage of using a method in this way is that you can apply validity
checks on the new value that is to be set.