CS 1063, Fall 2005
BankAccount class

The lectures for Week 5 had you work on a BankAccount class. Here is one version of that class. Additions not given in the notes are in red.

// BankAccount: handle balance and operations
public class BankAccount {
  // private data (instance variables) here
  private double myCurrentBalance;
 
  // Constructors
  // Constructs a bank account with a zero balance./
  public BankAccount() {
    // initialize current balance to 0
    myCurrentBalance = 0.0;
  }
  
  // Constructs a bank account with a given balance
  //    @param initialBalance the initial balance
  public BankAccount(double initialBalance) {
    // initialize current balance to initialBalance
    myCurrentBalance = initialBalance;
  }
 
  // methods
  // Deposits money into the bank account.
  //    @param amount the amount to deposit
  public void deposit(double amount){
    //  Add amount to balance
    myCurrentBalance = myCurrentBalance + amount;
  }
 
  // Withdraws money from the bank account
  //    @param amount the amount to withdraw
  public void withdraw(double amount){
    //  Subtract amount from balance
    myCurrentBalance = myCurrentBalance + amount;
  }
 
  // Gets the current balance of the bank account.
  //    @return the current balance
  public double getBalance(){
    //  Return balance
    return myCurrentBalance;  
  }
 
  // toString method allows printing class instance
  public String toString() {
    return "Current Balance: " + myCurrentBalance;
  }
}
public class BankAccountTest {

   public static void main(String[] args) {
      BankAccount account1 = new BankAccount();
      System.out.println("Account1 balance: " +
         account1.getBalance());
      BankAccount account2 = 
         new BankAccount(1200);
      System.out.println("Account2 balance: " +
         account2.getBalance());
      account2.deposit(500);
      System.out.println("Account2 balance: " +
         account2.getBalance());
      account2.withdraw(700);
      System.out.println("Account2 balance: " +
         account2.getBalance());
      // call toString method implicitly
      System.out.println(account2);
   }
}

Output:
Account1 balance: 0.0
Account2 balance: 1200.0
Account2 balance: 1700.0
Account2 balance: 1000.0
Current Balance: 1000.0