www.delorie.com/gnu/docs/smalltalk/gst_63.html   search  
Buy GNU books!

GNU Smalltalk User's Guide

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.4.5 Looking at our Account

Let's create an instance of class Account:
   Smalltalk at: #a put: (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. Let's take a look at the Account object we just created:
   a printNl !

It prints:
   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 methodsFor: 'printing'!
   printOn: stream
       super printOn: stream.
       stream nextPutAll: ' with balance: '.
       balance printOn: stream
   ! !

Now give it a try again:
   a printNl !

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.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003