Introduction to Object-Oriented Programming -2 Inheritance & Polymorphism

In this article, we’ll continue to look at Object-Oriented Programming- abbr. OOP-. The topics are Inheritance and Polymorphism. These topics are two of the primary characteristics of object-oriented programming.

  • Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes.
  • Polymorphism is a Greek word that means “many-shaped”. And it occurs when we have many classes that are related to each other by inheritance.

Inheritance

Inheritance is a concept in which you define parent classes and child classes. So, It is the mechanism by which one class is allowed to inherit the features (fields and methods) of another class. Inheritance gives us reusability. Reusability could be described as creating a new class by reusing the properties of the existing class.

We define the “inheritance concept” into two categories:

  • Derived Class (child) — the class that inherits from another class
  • Base Class (parent) — the class being inherited from

C#

We use a colon to inherit from another class and the parent class name to call the parent class.

JavaScript

We use extends to inherit from another class and the super keyword to call the parent class (function).

Most of the advantage of inheritance is reusability and it leads to less development and maintenance costs.

Polymorphism

The term polymorphism simply means ‘one function, multiple forms’. Inheritance lets us inherit fields and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

Types of Polymorphism are:

  • Compile-time polymorphism (Method overloading)
  • Run-time polymorphism (Method Overriding)

Let’s examine with the examples.

  1. Compile-time polymorphism (Method overloading)

C#

JavaScript

In JavaScript, overloading is slightly different because we cannot produce two different functions with the same name. (The Factory Pattern uses this type of Polymorphism).

2. Run-time polymorphism (Method Overriding)

C#

JavaScript

As you can see, the features of polymorphism mainly depend on the programming languages.

Conclusion

Inheritance is generating the child classes that take the properties and methods of the parent class. The child class can then also define its own methods.

Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding). It is applied to functions or methods.

Consequently, inheritance and polymorphism are interrelated concepts.

Full Stack Developer👨🏻‍💻 Camper 🏕️

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store