Exercise 3: Exploring Encapsulation, Version 2 (Level 2)
In this exercise, you explore the purpose of proper object encapsulation. These are level 2 instructions, which provide additional hints.
Task 1 - Modifying the Account
Class
Using a text editor, modify the Account
class source file. This class must satisfy the UML diagram in Figure 2.2
1. Change the balance instance variable from public to private
2. Add the deposit method that takes an amount (of type double) and adds that amount to the balance. Save the new balance in the instance variable
3. Add the withdraw
method that takes an amount (of type double) and substracts that amount
from the balance. Save the new balance in the instance variable.
This operation
might set the balance to a value below zero if the amount to withdraw
is larger than the current balance. You must use a conditional
statement to verify that the amount is not greater that the balance
before doing the substraction. The conditional statement looks like
this:
if ( <boolean_text> ) {
<statement_when_true>*
} else {
<statement_when_false>*
}
4.- Add the getBalance method to return the balance instance variable.
Task 2 - Modifying the TestAccount
Class
Remove the TestAccount2 program. This program will no longer work because you have made the balance instance variable private.
Using a text editor, modifiy the TestAccount program source file. Modify this program to deposit 47 and to withdraw 150.
1. Change the amount in the call to the deposit method to 47.0.
2. Change the amount in the call to the withdraw method to 150.0
Task 3 - Compiling the TestAccount
Program
On the command line, use the javac command to compile the test program and run the Account class.
Task 4 - Running th TestAccount
Program
On the command line, use java
command to run the test program. You should see the following output:
The final balance is 147.0
Notice that the 150 withdraw command did not take effect, because it would have made the balance drop below zero. However, the Account
object did no tell the program that the withdraw command failed, it
ignored the command. You will fix this problem in future exercises.