Previous: , Up: Creating subclasses  

6.5.3 Writing checks

We will finish this chapter by adding a method for spending money through our checkbook. The mechanics of taking a message and updating variables should be familiar:

   newChecks: number count: checkcount [
       <category: 'spending'>
       checknum := number.
       checksleft := checkcount

   writeCheck: amount [
       <category: 'spending'>
       | num |
       num := checknum.
       checknum := checknum + 1.
       checksleft := checksleft - 1.
       self spend: amount.
       ^ num

newChecks: fills our checkbook with checks. We record what check number we’re starting with, and update the count of the number of checks in the checkbook.

writeCheck: merely notes the next check number, then bumps up the check number, and down the check count. The message self spend: amount resends the message spend: to our own object. This causes its method to be looked up by Smalltalk. The method is then found in our parent class, Account, and our balance is then updated to reflect our spending.

You can try the following examples:

   c := Checking new
   c deposit: 250
   c newChecks: 100 count: 50
   c writeCheck: 32

For amusement, you might want to add a printOn: message to the checking class so you can see the checking-specific information.

In this chapter, you have seen how to create subclasses of your own classes. You have added new methods, and inherited methods from the parent classes. These techniques provide the majority of the structure for building solutions to problems. In the following chapters we will be filling in details on further language mechanisms and types, and providing details on how to debug software written in Smalltalk.