Before we go much further, let's make sure we fully understand the concept of inheritance in object-oriented programming. Class-based inheritance is demonstrated in the following pseudo-code:
class Polygon { int numSides; function init(n) { numSides = n; } } class Rectangle inherits Polygon { int width; int length; function init(w, l) { numSides = 4; width = w; length = l; } function getArea() { return w * l; } } class Square inherits Rectangle { function init(s) { numSides = 4; width = s; length = s; } }
The Polygon
class is the parent class the other classes inherit from. It defines just one member variable, the number of sides, which is set in the init()
function. The Rectangle
subclass inherits from the Polygon
class and adds two more member variables, length
and width
, and a method, getArea()
. It doesn't need to define the numSides
variable because it was already defined by the class it inherits from, and it also overrides the init()
function. The Square
class carries on this chain of inheritance even further by inheriting from the Rectangle
class for its getArea()
method. By simply overriding the init()
function again such that the length and width are the same, the getArea()
function can remain unchanged and less code needs to be written.
In a traditional OOP language, this is what inheritance is all about. If we wanted to add a color property to all the objects, all we would have to do is add it to the Polygon
object without having to modify any of the objects that inherit from it.