Next: , Previous: , Up: The hierarchy  


6.3.2 Animals

Imagine that we have three kinds of objects, representing Animals, Parrots, and Pigs. Our messages will be eat, sing, and snort. Our first pass at inserting these objects into the Smalltalk hierarchy would organize them like:

   Object
       Animals
       Parrots
       Pigs

This means that Animals, Parrots, and Pigs are all direct descendants of Object, and are not descendants of each other.

Now we must define how each animal responds to each kind of message.

       Animals
           eat –> Say “I have now eaten”
           sing –> Error
           snort –> Error
       Parrots
           eat –> Say “I have now eaten”
           sing –> Say “Tweet”
           snort –> Error
       Pigs
           eat –> Say “I have now eaten"”
           sing –> Error
           snort –> Say “Oink”

Notice how we kept having to indicate an action for eat. An experienced object designer would immediately recognize this as a clue that we haven’t set up our hierarchy correctly. Let’s try a different organization:

   Object
       Animals
           Parrots
                  Pigs

That is, Parrots inherit from Animals, and Pigs from Parrots. Now Parrots inherit all of the actions from Animals, and Pigs from both Parrots and Animals. Because of this inheritance, we may now define a new set of actions which spares us the redundancy of the previous set:

       Animals
           eat –> Say “I have now eaten”
           sing –> Error
           snort –> Error
       Parrots
           sing –> Say “Tweet”
       Pigs
           snort –> Say “Oink”

Because Parrots and Pigs both inherit from Animals, we have only had to define the eat action once. However, we have made one mistake in our class setup—what happens when we tell a Pig to sing? It says “Tweet”, because we have put Pigs as an inheritor of Parrots. Let’s try one final organization:

   Object
       Animals
           Parrots
           Pigs

Now Parrots and Pigs inherit from Animals, but not from each other. Let’s also define one final pithy set of actions:

       Animals
           eat –> Say “I have eaten”
       Parrots
           sing –> Say “Tweet”
       Pigs
           snort –> Say “Oink”

The change is just to leave out messages which are inappropriate. If Smalltalk detects that a message is not known by an object or any of its ancestors, it will automatically give an error—so you don’t have to do this sort of thing yourself. Notice that now sending sing to a Pig does indeed not say “Tweet”—it will cause a Smalltalk error instead.


Next: , Previous: , Up: The hierarchy