Java Reference
In-Depth Information
3.8 Implicit and Explicit Method Parameters
In
Section 2.4
, you learned that a method has an implicit parameterȌthe object on
which the method is invokedȌand explicit parameters, which are enclosed in
parentheses. In this section, we will examine these parameters in greater detail.
Have a look at a particular invocation of the
deposit
method:
momsSavings.
deposit(
500
);
Now look again at the code of the
deposit
method:
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
The parameter variable
amount
is set to 500 when the
deposit
method starts. But
what does
balance
mean exactly? After all, our program may have multiple
Bank-Account
objects, and each of them has its own balance.
Of course, since we deposit the money into
momsSavings
,
balance
must mean
momsSavings.balance
. In general, when you refer to an instance field inside a
method, it means the instance field of the object on which the method was called.
107
108
Thus, the call to the
deposit
method depends on two values: the object to which
momsSavings
refers, and the value
500
. The
amount
parameter inside the
parentheses is called an explicit parameter, because it is explicitly named in the
method definition. However, the reference to the bank account object is not explicit in
the method definitionȌit is called the implicit parameter of the method.
The implicit parameter of a method is the object on which the method is invoked.
The
this
reference denotes the implicit parameter.
If you need to, you can access the implicit parameterȌthe object on which the
method is calledȌwith the keyword
this
. For example, in the preceding method
invocation,
this
was set to
momsSavings
and
amount
was set to 500 (see
Figure
8
).