Difference between new and initialize in Smalltalk?

别来无恙 提交于 2019-12-08 17:07:27

问题


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


回答1:


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




回答2:


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




回答3:


Bavarious is correct.

Behavior >> new
        "Answer a new instance of the receiver.  If the instance can have indexable variables, it will have 0 indexable variables."

        "Primitive fails if the class is indexable."
        <primitive: 70>
        self isVariable ifTrue: [^self new: 0].
        self primitiveFailed

Object >> initialize
    "Initialize the object to its default state. This is typically used in a convention that the class implements the #new method to call #initialize automatically. This is not done for all objects in VisualWorks, but the initialize method is provided  here so that subclasses can call 'super initialize' and not get an exception."

    ^self.


来源:https://stackoverflow.com/questions/5692844/difference-between-new-and-initialize-in-smalltalk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!