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

GNU Smalltalk User's Guide

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

4.4.4 Defining an instance method

We need to define the init method for our Account objects, so that our new method defined above will work. Here's the Smalltalk code:
   !Account methodsFor: 'instance initialization'!
       balance := 0
   ! !

It looks quite a bit like the previous method definition, except that the first one said Account class methodsFor:..., and ours says Account methodsFor:....

The difference is that the first one defined a method for messages sent directly to Account, but the second one is for messages which are sent to Account objects once they are created.

The method named init has only one line, balance := 0. This initializes the hidden variable balance (actually called an instance variable) to zero, which makes sense for an account balance. Notice that the method doesn't end with ^r or anything like it: this method doesn't return a value to the message sender. When you do not specify a return value, Smalltalk defaults the return value to the object currently executing. For clarity of programming, you might consider explicitly returning self in cases where you intend the return value to be used.(25)

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