Java Reference
In-Depth Information
However, you should be aware of one common use of the
this
reference. When
implementing constructors, many programmers find it tiresome to come up with
different names for instance fields and parameters. Using the
this
reference
solves that problem. Here is a typical example.
public Coin(double value, String name)
{
this. value = value;
this.name = name;
}
360
361
The expression
this.value
refers to the instance field, but
value
is the
parameter. Of course, you can always rename the construction parameters to
aValue
and
aName
, as we have done in this topic.
S
ELF
C
HECK
16.
Consider the
deposit
method of the
BankAccount
class. What is
the scope of the variables
amount
and
newBalance
?
17.
What is the scope of the balance field of the
BankAccount
class?
C
OMMON
E
RROR
8.2: Shadowing
Accidentally using the same name for a local variable and an instance field is a
surprisingly common error. As you saw in the preceding section, the local
variable then shadows the instance field. Even though you may have meant to
access the instance field, the local variable is quietly accessed. For some reason,
this problem is most common in constructors. Look at this example of an
incorrect constructor:
public class Coin
{
public Coin(double aValue, String aName)
{
value = aValue;
String name = aName;
// Oops. . .
}
. . .
private double value;