27.9.2: Inheritance and Polymorphism
-
- Last updated
- Save as PDF
Overview
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object (prototypical inheritance) or class (class-based inheritance), retaining similar implementation. In most class-based object-oriented languages, an object created through inheritance (a “child object”) acquires all the properties and behaviors of the parent object (except: constructors, destructor, overloaded operators and friend functions of the base class). Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors (realizing an interface), to reuse code and to independently extend original software via public classes and interfaces. [1]
Discussion
Inheritance is a way of arranging objects in a hierarchy from the most general to the most specific. An object which inherits from another object is considered to be a subtype of that object. An example might include Instructor and Student, each of which inherit from Person. When we can describe the relationship between two objects using the phrase is-a , that relationship is inheritance.
We also often say that a class is a subclass or child class of a class from which it inherits, or that the other class is its superclass or parent class . We can refer to the most generic class at the base of a hierarchy as a base class .
Inheritance can help us to represent objects which have some differences and some similarities in the way they work. We can put all the functionality that the objects have in common in a base class, and then define one or more subclasses with their own custom functionality.
Inheritance is also a way of reusing existing code easily. If we already have a class which does almost what we want, we can create a subclass in which we partially override some of its behavior, or perhaps add some new functionality.
In some statically typed languages inheritance is very popular because it allows the programmer to work around some of the restrictions of static typing. If an instructor and a student are both a kind of person, we can write a function which accepts a parameter of type Person and have it work on both instructor and student objects because they both inherit from Person. This is known as polymorphism .
Key Terms
- inheritance
- An object or class being based on another object or class, using the same implementation or specifying a new implementation to maintain the same behavior. [2]
- polymorphism
- The provision of a single interface to entities of different types. [3]