Java Reference
In-Depth Information
without the
this
and a dot in front of each instance variable is just an abbreviation for
this version. However, the abbreviation of omitting the
this
is used frequently.
The keyword
this
is known as the
this
parameter
. The
this
parameter is a kind
of hidden parameter. It does not appear on the parameter list of a method, but is still a
parameter. When a method is invoked, the calling object is automatically plugged in
for
this
.
this
parameter
The
this
Parameter
Within a method definition, you can use the keyword
this
as a name for the calling object.
If an instance variable or another method in the class is used without any calling object,
then
this
is understood to be the calling object.
There is one common situation that requires the use of the
this
parameter. You
often want to have the parameters in a method such as
setDate
be the same as the
instance variables. A first, although incorrect, try at doing this is the following rewrit-
ing of the method
setDate
from Display 4.4:
public
void
setDate(
int
month,
int
day,
int
year) //Not correct
{
month = monthString(month);
day = day;
year = year;
}
This rewritten version does not do what we want. When you declare a local variable in
a method definition, then within the method definition, that name always refers to the
local variable. A parameter is a local variable, so this rule applies to parameters. Con-
sider the following assignment statement in our rewritten method definition:
day = day;
Both the identifiers
day
refer to the parameter named
day
. The identifier
day
does not refer to the instance variable
day
. All occurrences of the identifier
day
refer to the parameter
day
. This is often described by saying the parameter
day
masks
or hides the instance variable
day
. Similar remarks apply to the
parameters
month
and
year
.
This rewritten method definition of the method
setDate
will produce a compiler
error message because the following attempts to assign a
String
value to the
int
vari-
able (the parameter)
month
:
mask a
variable
month = monthString(month);
However, in many situations, this sort of rewriting will produce a method definition
that will compile but that will not do what it is supposed to do.