I’m writing documentation for an object-oriented language, and I wonder what kind of classes would be a good example for inheritance.
Some common examples:
class Person { } class Employee extends Person { }
Currently my favorite, but I don’t like Person->Employee because ‘Employee’ does not exactly look like fun.
class Bicycle { } class MountainBike extends Bicycle { }
I found this in some Java tutorial, but it’s not really obvious what attributes a bike should have.
class Animal { } class Bird extends Animal { }
Same as the bicycle.
class A { } class B extends A { }
Too abstract. The main problem is that such a class will need even more abstract attributes and methods.
Does anyone have a better example for a simple class hierarchy?
The Animal class is the classic example of class inheritance for a number of reasons.
First, there are obvious ways to extend the underlying animal class. You’ll likely start with sub-classes such as Mammal, Bird, Crustacean, etc.
Some classes, such as Mammal, will extend Animal by adding attributes that are fairly obvious (‘Warm-Blooded’, etc.).
Other, more problematic, issues that are quite common in developing a class hierarchy are quite obvious if you illustrate with animal inheritance – and this is a good thing for purposes of explanation. Birds fly, right? Well, not all birds… So, how do you represent flying? There are, of course, classic solutions and a wealth of discussion information online about how to solve the problems and tradeoffs that each solution introduces.
Thus, I would highly recommend using ‘Animal’ as your example because of the richness of available information and examples.