Next: , Previous: , Up: Creating classes  


6.4.5 Looking at our Account

Let’s create an instance of class Account:

   a := Account new

Can you guess what this does? The Smalltalk at: #a put: <something> creates a Smalltalk variable. And the Account new creates a new Account, and returns it. So this line creates a Smalltalk variable named a, and attaches it to a new Account—all in one line. It also prints the Account object we just created:

   an Account

Hmmm... not very informative. The problem is that we didn’t tell our Account how to print itself, so we’re just getting the default system printNl method—which tells what the object is, but not what it contains. So clearly we must add such a method:

    Account extend [
        printOn: stream [
            <category: 'printing'>
            super printOn: stream.
            stream nextPutAll: ' with balance: '.
            balance printOn: stream
        ]
    ]

Now give it a try again:

   a

which prints:

   an Account with balance: 0

This may seem a little strange. We added a new method, printOn:, and our printNl message starts behaving differently. It turns out that the printOn: message is the central printing function—once you’ve defined it, all of the other printing methods end up calling it. Its argument is a place to print to—quite often it is the variable Transcript. This variable is usually hooked to your terminal, and thus you get the printout to your screen.

The super printOn: stream lets our parent do what it did before—print out what our type is. The an Account part of the printout came from this. stream nextPutAll: ' with balance: ' creates the string with balance: , and prints it out to the stream, too; note that we don’t use printOn: here because that would enclose our string within quotes. Finally, balance printOn: stream asks whatever object is hooked to the balance variable to print itself to the stream. We set balance to 0, so the 0 gets printed out.


Next: , Previous: , Up: Creating classes