Java Reference
In-Depth Information
2.7. this
You have already seen (on page 52 ) how you can use an explicit con-
structor invocation to invoke another one of your class's constructors at
the beginning of a constructor. You can also use the special object refer-
ence this inside a non-static method, where it refers to the current object
on which the method was invoked. There is no this reference in a static
method because there is no specific object being operated on.
The this reference is most commonly used as a way to pass a reference
to the current object as an argument to other methods. Suppose a meth-
od requires adding the current object to a list of objects awaiting some
service. It might look something like this:
service.add(this);
The capture method in class Body also used this to set the value of the
victim's orbits field to the current object.
An explicit this can be added to the beginning of any field access or
method invocation in the current object. For example, the assignment to
name in the Body class two-argument constructor
name = bodyName;
is equivalent to the following:
this.name = bodyName;
Conventionally, you use this only when it is needed: when the name of
the field you need to access is hidden by a local variable or parameter
 
Search WWH ::




Custom Search