Exercise 3 w/ Solution
25/07/2009 14:41Creating 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.
Banking |
|
|||
|
- Create the banking directory. Use a command, such as:
md banking
- 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.
- Declare one private object attribute: balance; this attribute holds the current (or “running”) balance of the bank account.
- Declare a public constructor that takes one parameter (init_balance) that populates the balance attribute.
- Declare a public method getBalance that retrieves the current balance.
- Declare a public method deposit that adds the amount parameter to the current balance.
- Declare a public method withdraw that removes the amount parameter from the current balance.
- 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
- 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
SOLUTION.
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"); account.withdraw(150.00); System.out.println("Deposit 22.50"); account.deposit(22.50); System.out.println("Withdraw 47.62"); account.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
}
}
----end----
———
Back