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

In the next two exercises, you explore the purpose of proper object encapsulation. These are the Level 2 instructions, which provide additional hints.

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
  1. Declare the Account class
  2. Add the balance instance variable
  3. Add a constructor that sets the balance instance variable to the initial balance argument passed to the constructor

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.
  1. Declare the TestAccount2 class.
  2. Add the main method:
    1. Declare a variable withing the main method of type Account named acct. Also, in the same statement, initialize the variable acct to a new instance of Account by passing 100.00 to the constructor as the initial balance.
    2. Use the addition operator to add 47 to the account object's balance
    3. Use the substraction operator to substract 150 from the account object's balance
    4. Use the System.out.println method to display the balance 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