Newbie question - Constructors

Griggs, Travis tgriggs at keyww.com
Tue Aug 29 01:02:38 UTC 2000


Mark Greenaway wrote:

> I'm using Squeak to try to learn about Smalltalk. At the moment I'm trying to
> create a Frog class with a collection Frogs stored at class level. I want to
> somehow override Frog new so that when a Frog instance is created, the new
> method defined in the Frog class creates the object instance and then adds this
> instance to the Frogs collection.
>
> I've tried
>
> new
>         ^super new initialize
>
> initialize
>         self class Frogs add: self
>
> but the new defined in the Frog class is never called. Can someone please tell
> me what I'm missing? Is this even the right approach in Smalltalk?

It looks like you have a Frogs Class Variable? Here's how I'd do it:

Frog class>>initialize
    "self initialize"

    Frogs := Set new.

Frog class>>new
    | newFrog |
    Frogs ifNil: [self initialize].
    newFrog := super new setUp.
    Frogs add: newFrog.
    ^newFrog

Frog>>setUp
    "put any instance specific initialization in this method, such as..."

    legs := 4.
    age := 0.
    etc := #whatever

Note the difference between the class side methods and the instance side methods.
The first two are class side, and the last is instance side. The initialize method
is more of a utility. It simply sets up your froggie list. You can send it to the
class anytime in the future, to reset (or empty) your list of frogs.

When you send the message new to the class Frog it:
1) makes sure that you have a valid collection to add your new tadpoles to
2) sends the super implementation of new, which actually gives you the new chunk of
memory that is your new frog
3) sends the message setUp to the *instance* of your new frog (don't know what
state represents a frog, so I guessed)
    *note* that setUp implicitely returns self, or rather the instance
4) stores the result of message sends 2 and 3 (which should be your new froggie) in
a temporary variable called newFrog
5) sends the message add: to the Frogs collection with your newFrog as an argument.

6) returns the instance of the new frog to the caller

--
Travis Griggs (a.k.a. Lord of the Fries)
Member, Fravenic Skreiggser Software Collective
Key Technology
P-P-P-Penguin  Power!





More information about the Squeak-dev mailing list