Navigation:  Tutorials > Beginners Guide to Smalltalk > Programming in Smalltalk > Class Inheritance >

Is-a and Contains-a Relationships

Previous pageReturn to chapter overviewNext page

So, back to Animal. Where in the class hierarchy should we choose to create this class? The first thing to consider is what sort of information will each instance of Animal hold. Looking at the knowledge base diagram above we can see that each animal must at least know its name; i.e. what sort of animal it is. This will be in the form of a Smalltalk text String such as: 'Dog', 'Cat', 'Horse' etc. So, a possible location in the class hierarchy that we might consider would be to make Animal a subclass of String. To look at this decision in more detail, find the String class in the Class  Browser (remember you can do this using the Go Search bar) and take a look at the methods that are defined for all Strings.


If we make our Animal class a subclass of String then we will inherit all of these methods. This may, or may not, be what we want. Think about it; does it make sense for an Animal to understand messages such as #>= and #asNumber etc? No, not really!

What we should actually be asking is whether an Animal "is a" String or whether it, in fact, should "contain a" String. This is one of the fundamental decisions that software designers make when they are performing an "object oriented analysis" on a design problem. Often a problem is complex enough that it is worth drawing a diagram of the object model and this will illustrate the relationships between the various objects in the system. The relationships are often described as Is-a and Contains-a relationships.

It is my suggestion, therefore, that an Animal should contain a String and not be a subclass of one. So, we still haven't yet decided exactly where Animal should be subclassed in the overall hierarchy. In these situations it is best just to start off with your class being a direct subclass of Object (it is to represent an object after all). This is a very good default starting point. The great thing about Smalltalk is that, if you should later discover that there is a more suitable superclass somewhere in the image, then it is really easy to refactor and move your class to this new location in the hierarchy.