Java Reference
In-Depth Information
Let's walk through an example to demonstrate exactly how instance methods use
the implicit parameter. The following client code constructs two Point objects and
sets initial locations for them:
// construct two Point objects
Point p1 = new Point();
p1.x = 7;
p1.y = 2;
Point p2 = new Point();
p2.x = 4;
p2.y = 3;
After the preceding code has executed, the variables and objects in memory would
appear as follows (remember that each object has its own copy of the translate
method):
x
x 3
7 y 2
p1
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
x
x 3
4 y 3
p2
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
Now we'll call the translate method on each object. First, p1 is translated.
During this call, p1 's translate method is passed the parameters 11 and 6 . The
implicit parameter here is p1 's object, so the statements x += dx ; and y += dy ;
affect p1.x and p1.y :
p1.translate(11, 6);
x 3
x 18 y 8
p1
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
 
Search WWH ::




Custom Search