Next: A look at our object, Previous: Defining methods, Up: Creating classes
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.27
Before going on, ere is how you could have written this code in a
single declaration (i.e. without using extend
):
Object subclass: Account [ | balance | <comment: 'I represent a place to deposit and withdraw money'> Account class >> new [ <category: 'instance creation'> | r | r := super new. r init. ^r ] init [ <category: 'initialization'> balance := 0 ] ]
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.