Java Reference
In-Depth Information
During the second method call
p2
's
translate
method is executed, so the lines in
the body of the
translate
method change
p2.x
and
p2.y
:
p2.translate(1, 7);
x
x 3
5 y 10
p2
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
The
translate
method is an example of a
mutator.
Mutator
An instance method that modifies the object's internal state.
Generally, a mutator assigns a new value to one of the object's fields. Going back
to the radio example, the mutators would be the switches and knobs that turn the
radio on and off or change the station or volume.
It is a common convention for a mutator method's name to begin with “set,” as in
setID
or
setTitle
. Usually, a mutator method has a
void
return type. Mutators
often accept parameters that specify the new state of the object or the amount by
which to modify the object's current state.
Accessors
form a second important category of instance methods.
Accessor
An instance method that provides information about the state of an object
without modifying it.
Generally, an accessor returns the value of one of the object's fields. Using our
radio analogy, an accessor might return the current station or volume. Examples of
accessor methods you have seen in previous chapters include the
length
and
substring
methods of
String
objects and the
exists
method of
File
objects.
Our client program computes the distance of two
Point
s from the origin, (0, 0).
Since this is a common operation related to the data in a
Point
, let's give each
Point
object an accessor called
distanceFromOrigin
that computes and returns that
Point
object's distance from the origin. The method accepts no parameters and
returns the distance as a
double
.
The distance from the origin is computed using the Pythagorean Theorem, taking
the square root of the sum of the squares of the
x
and
y
values. As we did when we
Search WWH ::
Custom Search