Java Reference
In-Depth Information
The
translate
method can refer to
x
and
y
directly without being more specific
about which object it is affecting. It's as though you were riding inside a car and
wanted the driver to turn left; you'd simply say, “Turn left.” Though there are mil-
lions of cars in the world, you wouldn't feel a need to specify which car you meant. It
is implied that you mean the car you're currently occupying. Similarly, in instance
methods we don't need to specify which object's
x
or
y
we're using, because it is
implied that we want to use the fields of the object that receives the message.
Here's the complete
Point
class that contains the
translate
method. Sun's Java
style guidelines suggest declaring fields at the top of the class, with methods below,
but in general it is legal for a class's contents to appear in any order.
public class Point {
int x;
int y;
// shifts this point's location by the given amount
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
}
Here is the general syntax for instance methods:
public <type> <name>(<type> <name>, ..., <type> <name>) {
<statement>;
<statement>;
...
<statement>;
}
Methods like
translate
are useful because they give our objects useful behavior
that lets us write more expressive and concise client programs. Having the client code
manually adjust the
x
and
y
values of
Point
objects to move them is tedious, espe-
cially in larger client programs that translate many times. By adding the
translate
method, we have provided a clean way to adjust the location of a
Point
object in a
single statement.
The code for an instance method has an implied knowledge of the object on which it
operates. This knowledge is sometimes called the
implicit parameter.
Implicit Parameter
The object that is referenced during an instance method call.
Search WWH ::
Custom Search