2.8.9. Account management: overdraft protection
A convenient feature of some bank accounts is overdraft
protection; rather than bouncing a check when the balance
would go negative, the bank would deduct the necessary funds from
a second account. One might imagine such a setup for a
student account, provided the student's parents are willing to cover any
overdrafts (!).
Another use is to have a checking account
that is tied to a saving account, where the savings account
covers overdrafts on the checking account.
Implement and test overdraft protection for Account objects,
by completing the following steps.
-
Add a parentAccount instance variable to the Account
class; this is the account that will provide the overdraft protection,
and it may have overdraft protection of its own.
-
Add a two-argument constructor. The first argument will be the
initial balance as in the existing code. The second argument will be
an Account reference with which to initialize the instance
variable you defined in step 1.
-
In the one-argument constructor, set the parent account to null.
-
Modify the withdraw method so that, if the requested
withdrawal can't be covered by this account, the difference is
withdrawn from the parent account. This may trigger overdraft
protection for the parent account, and then its parent, and so onl you
are not allowed to assume a limit on the number of accounts connected
in this way. If the account doesn't have a parent and it can't cover
the withdrawal, the withdraw method should merely print an
error message as before and not change any account balances. Here's
an example of the desired behavior, with the Account object
kathy providing overdraft protection for the Account
object megan.
kathy balance |
megan balance |
attempted withdrawal from megan |
desired result |
500 |
100 |
50 |
megan has 50, kathy has 500 |
500 |
100 |
200 |
megan has 0, kathy has 400 |
500 |
100 |
700 |
return false without changing either balance |
Don't use a loop to implement this feature.
-
Add tests to AccountTester.java sufficient to exercise all
cases in the modified withdraw method.
-
Copy the updated Account.java and
AccountTester.java (including the merge method) to a
directory named day2. From within that directory, give the
command submit day2. All we want in the day2
directory are .java files.