Escolar Documentos
Profissional Documentos
Cultura Documentos
Here, this refers to the object on which get_pwr( ) was called. Thus, this.val refers to that
object's copy of val. For example, if get_pwr( ) had been invoked on x, then this in the
preceding statement would have been referring to x. Writing the statement without using
this is really just shorthand.
Here's the entire Pwr class written using the this reference:
Actually, no Java programmer would write Pwr as just listed because nothing is gained,
and the standard form is easier. However, this has some important uses.
For example, the Java syntax permits the name of a parameter or a local variable to be the
same as the name of an instance variable. When this happens, the local name hides the
instance variable.
You can gain access to the hidden instance variable by referring to it through this. For
example, although not recommended style, the following is a syntactically valid way to
write the Pwr( ) constructor.
In this version, the names of the parameters are the same as the names of the instance
variables, thus hiding them. However, this is used to "uncover" the instance variables.
Summary
In this lesson, you learned that when a method is called, it is automatically passed an
implicit argument that's a reference to the invoking object. This reference is called this.
You also learned that you can gain access to the hidden instance variable by referring to it
through this.