Java Reference
In-Depth Information
The Keyword this
When we discussed instance methods we mentioned that an object's instance meth-
ods can refer to its other methods and fields, because the instance method code
knows which object it's operating on. We called this idea the “implicit parameter.”
Now we will explore the mechanics behind the implicit parameter and introduce a
keyword that allows us to refer to it directly.
The implicit parameter is actually a special reference that is set each time an
instance method is called. You can access this reference in your code using the
keyword this .
this
A Java keyword that allows you to refer to the implicit parameter inside a
class.
When you refer to a field such as x in your code, you are actually using shorthand.
The compiler converts an expression such as x to this.x . You can use the longer
form in your code if you want to be more explicit. For example, our translate
method could be rewritten as follows:
public void translate(int dx, int dy) {
this.x += dx;
this.y += dy;
}
The code behaves the same way as the original version of the method. The explicit
style is less common, but some programmers prefer it because it's clearer. It also
more closely matches the style used in client code, where all messages to objects
begin with a variable name and a dot.
The general syntax for using the keyword this to refer to fields is
this.<field name>
Similarly, when you call an instance method such as translate , you're actually
using shorthand for a call of this.translate . You can use the longer form if you
prefer. It has the following general syntax:
this.<method name>(<expression>, <expression>, ..., <expression>);
When the implicit parameter was introduced, we diagrammed the behavior of
some method calls on two Point objects. Let's revisit the same example using the
keyword this . Consider the following two Point objects:
Point p1 = new Point(7, 2);
Point p2 = new Point(4, 3);
 
Search WWH ::




Custom Search