Phils quick-n-dirty intro to object-oriented thinking #6 - inheritance

This chapter is not done yet. [started, march 31, 2005]

In it, I will discuss object inheritance.

If it is not done in a month, bug me please :)


An example of bad objects

Let's say for some reason, you have to have representations of certain physical things. For some reason, the things you care about, are elephants, and oranges. Your first impulse might be to make a object class "Thing", that is a class that could represent both an Elephant, and an Orange.

To do anything useful with this object, you would need some very specific operators. For example, "ThingElephantFeed()", and "ThingOrangePeelit()". However, it makes no sense to try to use ThingElephantFeed(), if the object is currently representing an Orange. Because of this, "Thing" would then need special status queries, "isElephant()", and "isOrange()", to determine which would be the "right" operators to call on it.

This would certainly work. But it is very poor design. Firstly, it requires the programmer to know what this object "really" was, in order to call the "correct" functions for it. After the detailed object type is known, the programmer uses the object in completely different ways. This is a sign of a poor object design choice.

You might choose to have "Thing" be a parent class, and have separate Elephant and Orange classes that are derived from the "Thing" object. However... what would be left in Thing, that would be common to both Elephants and Oranges? Unless you are doing some very unusual modelling, the answer is probably "nothing". This indicates that they should not share a common parent class.

There is no reason in this simplified case to make an elephant, and an orange, share a common class. If you are set on making more general classes first, it might make more sense to have an Animal class, and a Food class (based on the assumption that down the road, you would be interested in more types of animals, and more types of food object. Then Animal would have a "Feed()" function, and Food could have "ShedWrapping()" function.

Once again, if you find yourself using a single object type, in vastly different ways, for different instances of objects, you probably should not be using a single object type in the first place.


I hope this has been useful to you. If you'd like another chapter added, email the author, below, with a suggested topic.
OOP Table of Contents --- phil@bolthole.com
Part of bolthole.com... Solaris tips ... ksh tutorial ... AWK Programming tutorial