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?
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.
Stuart answered it perfectly. But if you have still doubt about your second question:
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?
If you use something like Kent Beck's Constructor Parameter Method idiom for example in Pharo, where #initialize
is sent from #new
(as described by Stuart's answer):
Point class>>x: xNumber y: yNumber
^self new
setX: xNumber
y: yNumber
Point>>setX: xNumber y: yNumber
x := xNumber.
y := yNumber.
^self
Then first your initialize method will be called and only afterwards your Constructor Parameter Method will be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With