Java Reference
In-Depth Information
}
private double interestRate;
}
You may wonder why the
addInterest
method calls the
getBalance
and
deposit
methods rather than directly updating the
balance
field of the
superclass. This is a consequence of encapsulation. The
balance
field was defined
as
private
in the
BankAccount
class. The
addInterest
method is defined in
the
SavingsAccount
class. It does not have the right to access a private field of
another class.
441
442
Note how the
addInterest
method calls the
getBalance
and
deposit
methods of the superclass without specifying an implicit parameter. This means that
the calls apply to the same object, that is, the implicit parameter of the
addInterest
method. For example, if you call
collegeFund.addInterest();
then the following instructions are executed:
double interest =
collegeFund.
getBalance()
*
collegeFund.
interestRate / 100;
collegeFund.
deposit(interest);
In other words, the statements in the
addInterest
method are a shorthand for the
following statements:
double interest =
this.
getBalance()
*
this.
interestRate / 100;
this.
deposit(interest);
(Recall that the
this
variable holds a reference to the implicit parameter.)
S
ELF
C
HECK
1.
Which instance fields does an object of class
SavingsAccount
have?
2.
Name four methods that you can apply to
SavingsAccount
objects.
3.
If the class
Manager
extends the class
Employee
, which class is the
superclass and which is the subclass?