Smalltalk中new和initialize之间的区别?

时间:2011-04-17 09:58:16

标签: smalltalk

一个新手问题,new和initialize有什么区别?

3 个答案:

答案 0 :(得分:8)

完全。当您发送消息#new时,它不仅会创建对象,还会发送#initialize信息。这使您可以自定义对象的初始化。看:

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

然后:

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

   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"

所以...... #basicNew是创建对象的原语。通常,你使用#new,如果你不想要任何特殊的东西,你就不会实现#initialize,因此会执行#ProtoObject的空实现。否则,您可以直接发送#basicNew,但您可能不应该这样做。

干杯

答案 1 :(得分:5)

使用new创建一个新Object,而在创建新Object时执行initialize方法,并初始化Object。

答案 2 :(得分:3)

巴伐利亚是正确的。

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.