Exercise 3: Exploring Encapsulation, Version 2 (Level 1)

In this exercise, you explore the purpose of proper object encapsulation. You will modify
Accountclass to hide its data member and provide public methods to manipulate the balance. You will then use the test program that you created in Module 1 to test that the business rule (balance must not fall below zero) is satisfied.

Figure 2-2 shows the UML class diagram of the Account class that you will create. This design for the Account class hides the instance variable, balance, and supplies public methods to manipulate the account balance. The deposit method adds money to the account. The withdraw method removes money from the account. The getBalance method returns the current value of the balance instance variable.

Account
 -balance
<<constructors>>
+Account(initBalance:double)
<<methods>>
+getBalance(): double
+deposit(amt: double):void
+withdraw(amt: double):void

Figure 2-1 UML Class Diagram of Account with Information Hiding

Rembember: there is still one business rule that must be maintained: the balance of the bank account must never go below zero. Which method must guarantee this business rule?

Preparation

There is no preparation for this exercise.

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

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, modify the TestAccount program source file. Modify this program to deposit 47 and to withdraw 150.

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.