Java Reference
In-Depth Information
Often, the
this
reference is used to distinguish the parameters of a constructor
from their corresponding instance variables with the same names. For example,
the constructor of the
Account
class was presented in Chapter 4 as follows:
public
Account (String owner,
long
account,
double
initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
When writing this constructor, we deliberately came up with different names for
the parameters to distinguish them from the instance variables
name
,
acctNumber
,
and
balance
. This distinction is arbitrary. The constructor could have been writ-
ten as follows using the
this
reference:
public
Account (String name,
long
acctNumber,
double
balance)
{
this
.name = name;
this
.acctNumber = acctNumber;
this
.balance = balance;
}
In this version of the constructor, the
this
reference specifically refers to the
instance variables of the object. The variables on the right-hand side of the assign-
ment statements refer to the formal parameters. This approach eliminates the need
to come up with different yet equivalent names. This situation sometimes occurs
in other methods but comes up often in constructors.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 7.10
Describe a dependency relationship between two classes.
SR 7.11
Explain how a class can have an association with itself.
SR 7.12
What is an aggregate object?
SR 7.13
What does the
this
reference refer to?
We've used the term interface to refer to the set of public methods through which
we can interact with an object. That definition is consistent with our use of it in
this section, but now we are going to formalize this concept using a particular
language construct in Java.
Search WWH ::
Custom Search