Java Reference
In-Depth Information
and any parameters that the method accepts. Here's the start of a
Point
class with a
translate
method, with the header declared but the body blank:
public class Point {
int x;
int y;
public void translate(int dx, int dy) {
...
}
}
When we declare a
translate
method in the
Point
class, we are saying that
each
Point
object has its own copy of that method. Each
Point
object also has its
own
x
and
y
values. A
Point
object would look like the following:
x
x 3
7 y 2
public void translate(int dx, int dy) {
...
}
Whenever an instance method is called, it is called on a particular object. So, when
we're writing the body of the
translate
method, we'll think of that code from the
perspective of the particular
Point
object that receives the message: “The client has
given me a
dx
and
dy
and wants me to change my
x
and
y
values by those amounts.”
Essentially, we need to write code to match the following pseudocode:
public void translate(int dx, int dy) {
add dx to this Point object's x value.
add dy to this Point object's y value.
}
It's helpful to know at this point that an object's instance methods can refer to its
fields. In previous chapters we've talked about
scope,
the range in which a variable
can be seen and used. The scope of a variable is the set of braces in which it is
declared. The same rule applies to fields: Since they are declared directly inside a
class, their scope is the entire class.
This rule means that the
translate
method can directly refer to the fields
x
and
y
.
For example, the statement
x += 3
; would increase the
Point
object's
x
value by
3
.
Here is a working
translate
method that adjusts the
Point
object's location:
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
Search WWH ::
Custom Search