Search code examples
smalltalkgnu-smalltalk

When is initialize invoked in smalltalk?


I have a class with instance variable 'a'.

When i create a new instance of the class using new, what is the order of the methods that are called?

How will the object know that it should call the initialize method?

If I create a class method to assign values to my instance variables, will the initialize still be called for other instance variables that are not invoked by my class method?


Solution

  • initialize is usually called by the new method itself.

    I believe the standard implementation is:

    new
        ^self basicNew initialize
    

    #basicNew is a primitive that just creates the object, but does no initialization. All instance variables will be nil after basicNew.

    Note that the initialize method isn't called automatically in all implementations of Smalltalk (but I don't know which ones don't do it) so if you want to be properly portable, you should override #new in your classes to explicitly call it.