This is a good time to look at what we’ve done with the two previous examples at a higher level. With the NiledArray class, we inherited almost all of the functionality ality of arrays, with only a little bit of code added to address our specific needs. While you may have not thought to try it, all the existing methods for an Array continue to work without further effort-you might find it interesting to ponder why the following still works:
a := NiledArray new: 10 a at: 5 put: 1234 a do: [:i| i printNl ]
The strength of inheritance is that you focus on the incremental changes you make; the things you don’t change will generally continue to work.
In the Complex class, the value of polymorphism was exercised. A Complex number responds to exactly the same set of messages as any other number. If you had handed this code to someone, they would know how to do math with Complex numbers without further instruction. Compare this with C, where a complex number package would require the user to first find out if the complex-add function was complex_plus(), or perhaps complex_add(), or add_complex(), or…
However, one glaring deficiency is present in the Complex class: what happens if you mix normal numbers with Complex numbers? Currently, the Complex class assumes that it will only interact with other Complex numbers. But this is unrealistic: mathematically, a “normal” number is simply one with an imaginary part of 0. Smalltalk was designed to allow numbers to coerce themselves into a form which will work with other numbers.
The system is clever and requires very little additional
code. Unfortunately, it would have tripled the
amount of explanation required. If you’re interested in how
coercion works in GNU Smalltalk, you should find the
Smalltalk library source, and trace back the execution of
retry:coercing: messages. You want to consider the
value which the
generality message returns for each type
of number. Finally, you need to examine the
in each numeric class.