Bank Accounts

My favorite way of introducing OOP is to use bank accounts. A bank account (or, perhaps more accurately, a piggy bank) is a relatively simple idea:

  • data: it has a certain amount of money in it, the balance
  • behaviors:
    • you can deposit money (and the balance goes up)
    • you can withdraw money (and the balance goes down, or there's an error)

We can add additional behaviors (adding interest or fees, FDIC insurance, a free toaster when you open an account...) but this will do for now.

Implementation

The implementation is nearly as straightforward as the English description:

class Account {
    // instance variables
    balance = 0;

    constructor (init) {
        this.balance = init;
    }
    deposit (amount) {
        this.balance += amount;
    }
    withdrawal (amount) {
        if( this.balance >= amount ) {
            this.balance -= amount;
        } else {
            throw new Error("Insufficient funds");
        }
    }
} // end class

// Some examples
var harry = new Account(1000);
var ron = new Account(2);
var hermione = new Account(200);

Exercises/Examples

Try the following examples. I have loaded the class definition and the three example accounts of harry, ron and hermione into this page. You can open up a JS console and play with those values and a make others.

Start with these:

// Harry gives Ron 10 galleons
harry.withdrawal(10);
ron.deposit(10);

// create an account for Cho Chang
cho = new Account(200);
cho.withdrawal(50); // money for a new broom