簡體   English   中英

Smalltalk中new和initialize之間的區別?

[英]Difference between new and initialize in Smalltalk?

一個新手問題,new和initialize有什么區別?

究竟。 當您發送消息#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,但您可能不應該這樣做。

干杯

使用new,您可以創建一個新Object,而初始化方法在創建新Object時執行,並初始化Object。

巴伐利亞是正確的。

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM