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

In the next two exercises, you explore the purpose of proper object encapsulation. You create a class in two steps demonstrating the use of information hiding. In this version, you will create an Account class with public data members. You will then create a test program that demonstrates the danger of using the public data directly.

Figure 2-1 shows the UML class diagram of the Account class that you will create in this exercise. This class will have one public data member (or instance variable), called balance, that maintains the monetary value of the customer's bank account.

Account
 +balance
<<constructors>>
+Account(initBalance:double)

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

There is only one business rule that applies to the Account class: the balance of the bank account must never go below zero. In this exercise, you will discover that the Account class cannot ensure this business rule.

Preparation

Before you begin, make sure you have changed directories to projects/BankingPrj/ using the cd command in the terminal window.

cd ~/projects/BankingPrj/

Task 1 - Creating the Account Class

Using a text editor, create the Account class source file. This class must satisfy the UML diagram in Figure 2.1

Task 2 - Creating the TestAccount2 Class

Using a text editor, create the TestAccount2 program source file. This class acts as a program to create an Account object with an initial balance of 100. The test program will then add 47 and then substract 150. Finally, the test program must print out the balance of the object to the standard output stream.

Task 3 - Compiling the TestAccount2 Program

On the command line, use the javac command to compile the test program and run the Account class.

Task 4 - Running th TestAccount2 Program

On the command line, use java command to run the test program. You should see the following output:

The final balance is -3.0