Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between new and initialize in Smalltalk?

Tags:

smalltalk

A newbie question, what is the difference between new and initialize?

like image 284
oscarkuo Avatar asked Apr 17 '11 09:04

oscarkuo


2 Answers

Exactly. When you send the message #new, it not only creates the object, but sends the messagge #initialize. This let you customize the initialization of objects. Look:

Behavior >> new
"Answer a new initialized instance of the receiver (which is a class) with no indexable variables. Fail if the class is indexable."

^ self basicNew initialize

And then:

 ProtoObject >> initialize
"Subclasses should redefine this method to perform initializations on instance creation" 

And:

   Behaviour >> basicNew
"Primitive. Answer an instance of the receiver (which is a class) with no 
indexable variables. Fail if the class is indexable. Essential. See Object 
documentation whatIsAPrimitive."

<primitive: 70>
self isVariable ifTrue: [ ^ self basicNew: 0 ].
"space must be low"
OutOfMemory signal.
^ self basicNew  "retry if user proceeds"

So...#basicNew is the primitive that creates the object. Normally, you use #new and if you don't want anything in special, you don't implement #initialize and hence the empty implementation of #ProtoObject will be executed. Otherwise, you can directly send #basicNew but you probably shouldn't do this.

Cheers

like image 182
Mariano Martinez Peck Avatar answered Sep 21 '22 06:09

Mariano Martinez Peck


With new you create a new Object, while the initialize method is executed when the new Object is created, and initializes the Object.

like image 25
Tommy Avatar answered Sep 20 '22 06:09

Tommy