Java Reference
In-Depth Information
After constructing the Point objects, we make the following method calls:
p1.translate(11, 6);
p2.translate(1, 7);
Essentially, the behavior of these two method calls is the following:
Set this to refer to the same object as p1 , and execute the translate method
with parameters (11, 6) .
Set this to refer to the same object as p2 , and execute the translate method
with parameters (1, 7) .
During the first call, this refers to the same object as p1 . Therefore, the method
call adjusts the (x, y) coordinates of p1 's object:
p1
x 3
x 18
y 8
p2
x 3
x 4
y 3
<methods>
<methods>
this
During the second method call this refers to the same object as p2 , so the lines in
the body of the translate method change the x and y fields of p2 's object:
p1
x 3
x 18
y 8
p2
x 3
x 5
y 10
<methods>
<methods>
this
One common usage of the keyword this is to deal with shadowed variables. As
described earlier, shadowing occurs when a field is obscured by another variable with
the same name. Shadowing can happen when a field has the same name as a para-
meter or local variable in a class. For example, the following is a legal header for our
Point method, even though our fields are also called x and y :
public Point(int x, int y) {
As explained at the beginning of this section, Java would normally interpret the
expression x to mean this.x . However, if a parameter or local variable called x
exists, the program will use that one instead if you just write x, because the field x is
shadowed by the parameter/variable. If you write this.x , though, the program will
always use the field x .
Search WWH ::




Custom Search