What is Inheritance? A Simple OOP Explanation

Two object-oriented programming principles down (read about abstraction here and encapsulation here), two more to go! Today we?re going to be taking a look at inheritance. Compared to abstraction and encapsulation, inheritance is a bit more straightforward (in my personal opinion).

As with the other principles of OOP, inheritance is meant to optimize the work of programmers. The role that inheritance plays in this optimization is in allowing software engineers to create class hierarchies, where classes and objects inherit properties and behaviors from their parent (or super) class. A class that inherits from a parent (or super) class is called a subclass or child class, and objects that receive properties and behaviors from a parent through inheritance are referred to as child objects.

Image for post

How is this helpful? A big part of the usefulness of inheritance is reusability. I?m going to use Noah and the ark as an example. For those of you not familiar with the story, the Earth is threatened with a worldwide flood and Noah builds an ark in order to store two of every land faring animal on Earth so that they will survive the storm. Let?s say Noah wanted to use a software program to help him keep track of all the animals on the ark and their various needs.

Image for postPictured: a historically accurate artists rendition of Noah?s Ark (Photo by Dan Kb on Unsplash)

Creating a unique class for every single animal would quickly get very repetitious because there are some properties and behaviors that apply to every single animal, from a mouse to an elephant. Shared functions might include feed( ), hydrate( ), cleanEnclosure( ). Instead of creating these shared attributes over and over for every animal, we could instead create a parent Animal class! This parent class would contain the properties and behaviors universal to all animals and save us from having to create those shared functions ad infinitum.

Image for postmaybe a dontGetEaten( ) function would be helpful (Photo by Andre Klimke on Unsplash)

In this way, an elephant, a mouse, and a chimpanzee would all have their own child class which would inherit from the Animal parent class. Furthermore, Noah could continue to build on those inherited attributes to further customize these classes as necessary. Lastly, inheritance allows us to limit the chances of human error that might arise if manually inputting these shared functions.

Next week: polymorphism!

2

No Responses

Write a response