Exercise 3 w/ Solution

25/07/2009 14:41

Creating a Simple Bank Package

In this exercise, you create a simple version of the Account class. You place this source file in the banking package. A test program, TestBanking, has been written in the default package that creates a single account. It initializes the baance of that account and performs several simple transactions. Finally, the test program displays the final balance of the account.




- balance : double

+ Account(init_balance : double)

+ getBalance ( ) : double

+ deposit (amt : double)

+ withdraw (amt : double)

  1. Create the banking directory. Use a command, such as:

md banking

  1. Create the Account class in the file Account.java under the banking directory. This class must implement the model in the UML diagram shown above.
    1. Declare one private object attribute: balance; this attribute holds the current (or “running”) balance of the bank account.
    2. Declare a public constructor that takes one parameter (init_balance) that populates the balance attribute.
    3. Declare a public method getBalance that retrieves the current balance.
    4. Declare a public method deposit that adds the amount parameter to the current balance.
    5. Declare a public method withdraw that removes the amount parameter from the current balance.
  2. In the main exercise 3 Directory, compile the TestBanking.java file. This has a cascading effect of compiling all of the classes used in the program; therefore, compiling the Account.java file under the banking directory.

Javac –d . TestBanking.java

  1. Run the TestBanking class. You should see the following output:

Creating an account with a 500.00 balance.

Withdraw 150.00

Deposit 22.50

Withdraw 47.62

The account has a balance of 324.88




main code:

 * This class creates the program to test the banking classes.
 * It creates a new Bank, sets the Customer (with an initial balance),
 * and performs a series of transactions with the Account object.

import banking.*;

public class TestBanking {

  public static void main(String[] args) {
    Account  account;

    // Create an account that can has a 500.00 balance.
    System.out.println("Creating an account with a 500.00 balance.");
    account = new Account(500.00);

    System.out.println("Withdraw 150.00");

    System.out.println("Deposit 22.50");

    System.out.println("Withdraw 47.62");

    // Print out the final account balance
    System.out.println("The account has a balance of " + account.getBalance());


Class code:

public class Account {

private double balance;

public Account(double init_balance){
balance = init_balance;

public double getBalance(){
return balance;

public double deposit (double amt){
balance = balance + amt;

return balance;


public double withdraw (double amt){
balance = balance - amt;
return balance