/* bankacct.cc */ /* First, the scheme version (from Abelson & Sussman). (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (sequence (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request" m)))) dispatch) */ import java.io.*; class Account { /** Create a new account, with given initial balance. */ public Account(int initBalance) { balance = initBalance; } /** deposit amount from account. */ public void deposit(int amount) { balance += amount; } /** Withdraw amount from account, unless there are insufficient */ /* funds, in which case an error is printed. */ public void withdraw(int amount) { if (balance >= amount) { balance -= amount; } else { System.out.println("Insufficient funds"); } } /** Print statement on standard output. */ public void statement() { System.out.println("Current balance is " + balance); } /** transfer fund from other Account to this one. */ public void transfer(Account other, int amount) { if (other.balance > amount) { balance += amount; other.balance -= amount; } else { System.out.println("Insufficient funds"); } } /* invariant: balance >= 0 */ private int balance; } class BankTest { public static void main (String[] argv) { int amt; Account myAcct = new Account(200); myAcct.statement(); myAcct.deposit(100); myAcct.statement(); myAcct.withdraw(50); myAcct.statement(); Account yourAcct = new Account(1000); yourAcct.statement(); myAcct.transfer(yourAcct,500); myAcct.statement(); yourAcct.statement(); } }