Java Reference
In-Depth Information
anAccount.withdraw(1000);
anotherAccount.deposit(1000);
Depending on the actual types of
anAccount
and
anotherAccount
, different
versions of the
withdraw
and
deposit
methods are called.
455
456
If you look into the implementation of the
transfer
method, it may not be
immediately obvious that the first method call
withdraw(amount);
depends on the type of an object. However, that call is a shortcut for
this.withdraw(amount);
The
this
parameter holds a reference to the implicit parameter, which can refer to a
BankAccount
or a subclass object.
The following program calls the polymorphic
withdraw
and
deposit
methods.
You should manually calculate what the program should print for each account
balance, and confirm that the correct methods have in fact been called.
ch10/accounts/AccountTester.java
1 /**
2
This program tests the
BankAccount
class and
3
its subclasses.
4 */
5
public class
AccountTester
6 {
7
public static void
main(String[] args)
8 {
9 SavingsAccount momsSavings
10 =
new
SavingsAccount(
0.5
);
11
12 CheckingAccount harrysChecking
13 =
new
CheckingAccount(
100
);
14
15 momsSavings.deposit(
10000
);
16
17 momsSavings.transfer(
2000
,
harrysChecking);
18 harrysChecking.withdraw(
1500
);