Accounts

Roman E. Maeder

This notebook shows the use of the package Classes.m. The example is taken from my article in the Mathematica Journal, Vol. 3, No. 1.

Setup

You may have to set $Path first.

Needs["Classes`"]

Simple Accounts

An account is created by a call to the factory method new. It in turn will call the method new of its superclass. This is recommended to make sure that the object is properly initialized, even if we know (by peeking at the implementation) that the default implementation for new in class Object does nothing.

Class[ Account, Object,
       {bal, own},
       {
        {new,      (new[super]; bal = #1; own = #2)&},
        {balance,  bal&},
        {deposit,  Function[bal += #1]},
        {withdraw, Function[bal -= #1]},
        {owner,    own&}
       }
]

Here, we create an account . The return value is an opaque type.

a1 = new[Account, 100, "Roman E. Maeder"]

Methods are called like ordinary functions.

balance[a1]

deposit[a1, 50]

A Subclass

This subclass inherits most methods and all instance variables from its superclass. The method for withdrawing amounts is overridden, to check that the balance is sufficient. If it is we call the same method form the superclass, otherwise we print an error message.

Class[ NoCreditAccount, Account,
	{},
	{
	 {withdraw, Function[ If[ balance[self] < #1,
	                          Print["cannot withdraw ", #1],
	                          withdraw[super, #1] ]
	                    ]}
	}
]

b1 = new[NoCreditAccount, 1000, "Stephen Wolfram"]

withdraw[b1, 1100]

withdraw[b1, 900]