Object-Oriented Programming Concepts: A Primer |
Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars and pedals.Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. For example, mountain bikes, race bikes and tandems are all different kinds of bicycles. In object-oriented terminology, mountain bikes, race bikes and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, race bikes and tandems.
Each subclass inherits state (in the form of variable declarations) from the superclass. Mountain bikes, race bikes and tandems share some states: cadence, speed and the like. Also, each subclass inherits methods from the superclass. Mountain bikes, race bikes and tandems share some behaviours: braking and changing pedaling speed.
However, subclasses are not limited to the state and behaviours provided to them by their superclass. (What would be the point in that?) Subclasses can add variables and methods to the ones they inherited from the superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio.
Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could actually use those new gears.
You are not limited to just one layer of inheritance--the inheritance tree, or class hierarchy, can be as deep as needed. Methods and variables are inherited down through the levels. The further down in the hierarchy a class appears, the more specialized its behaviour.
The Benefit of Inheritance
- Subclasses provide specialized behaviours from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.
- Programmers can implement superclasses that define "generic" behaviours (called abstract classes). The essence of the superclass is defined and may be partially implemented but much of the class is left undefined and unimplemented. Other programmers fill in the details with specialized subclasses.
Table of Contents |