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

In this exercise, you explore the purpose of proper object encapsulation. These are level 3 instructions, which provide additional hints with code snippets.

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
    private double balance;
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.
    public void deposit (double amt) {
        balance = balance + amt;
 }
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.
public void withdraw (double amt){
    if ( amt <= balance) {
        balance = balance - amt;
    }   

}
4.- Add the getBalance method to return the balance instance variable.
public double getBalance(){
    return balance;

}

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.

del TestAccount2.*

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
        acct.deposit(47.0);
    2. Change the amount in the call to the withdraw method to 150.0

        acct.withdraw(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.

javac TestAccount.java

Task 4 - Running th TestAccount Program

On the command line, use java command to run the test program. 

java TestAccount

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.