Replacement Example - sqrt in Smalltalk

Here is an example of what we mean by replacement. This example is taken from Smalltalk, although the ideas are found in many languages. In Smalltalk numbers are placed in a hierarchy, with an abstract class Number at the top, and Integer and Float as child classes.

The class Number defines a method called sqrt, for computing square roots. This method is implemented by a procedure that says, in effect, convert myself into a floating point value, and then send the message square root to the result.

The method is overridden in the class Float so as to invoke a primitive (that is, a system call) that performs the actual work.

Now, this approach only works because Smalltalk uses replacement semantics. The code in the class Float completely hides the code in the parent class, and so for floating point values the parent class will never be executed. Were this not the case, computing a square root would always result in an infinite loop.

[audio] [real] Text to accompany slide4, in Chapter 11 of An Introduction to Object-Oriented Programming