To support
(DiceHandle new add: (Dice faces: 4); yourself)
+ (DiceHandle new add: (Dice faces: 6); yourself)
We defined +
as
DiceHandle >> + aDiceHandle
| handle |
handle := DiceHandle new.
self dice do: [ :each | handle addDice: each ].
aDiceHandle dice do: [ :each | handle addDice: each ].
^ handle
Between
DiceHandle >> + aDiceHandle
| handle |
handle := DiceHandle new.
And
DiceHandle >> + aDiceHandle
| handle |
handle := self class new.
Let us see....
DiceHandle subclass: MemoDiceHandle
....
(MemoDiceHandle new add: (Dice faces: 4); yourself)
+ (MemoDiceHandle new add: (Dice faces: 6); yourself)
> aDiceHandle
We get a DiceHandle
instance back and not a MemoDiceHandle
instance!!!
DiceHandle >> + aDiceHandle
| handle |
handle := self handleClass new.
self dice do: [ :each | handle addDice: each ].
aDiceHandle dice do: [ :each | handle addDice: each ].
^ handle
DiceHandle >> handleClass
^ DiceHandle
A subclass may redefine handleClass
MemoDiceHandle >> handleClass
^ MemoDiceHandle
(MemoDiceHandle new add: (Dice faces: 4); yourself)
+ (MemoDiceHandle new add: (Dice faces: 6); yourself)
> aMemoDiceHandle
We get an instance of the subclass!
Let us see
handleClass
DiceHandle >> + aDiceHandle
| handle |
handle := self class new.
self dice do: [ :each | handle addDice: each ].
aDiceHandle dice do: [ :each | handle addDice: each ].
^ handle
self class
always returns the class of the receiver
If we define a subclass of DiceHandle
,
and send the message +
to an instance
DiceHandle new
, +
does not return an instance of the subclass but of DiceHandle
self class new
, +
returns an instance of the receiver: an instance of a potential subclass/