Next: , Previous: Defining methods, Up: Creating classes

6.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 extend [
         init [
             <category: 'initialization'>
             balance := 0

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

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.1


[1] And why didn't the designers default the return value to nil? Perhaps they didn't appreciate the value of void functions. After all, at the time Smalltalk was being designed, C didn't even have a void data type.