What is inheritance? Types of inheritance

Inheritance represents the relationship between two objects or two classes where one derives functionality from another and then extends it by adding new fields, properties or methods. It is one of the fundamental concepts of the object-oriented programming along with polymorphism, abstraction and encapsulation. Inheritance allows classes to inherit commonly used state and behavior from other classes, so it is one of the main tools of code reuse in OOP.

Inheritance can be object-based (prototypal inheritance) and class-based.

Class-based inheritance enables new classes to take on the properties and behavior of existing classes. A class that is used as the basis for inheritance is called a superclass, parent or base class. A class that inherits from a superclass is called a subclass, child or derived class. A child inherits visible properties and methods from its parent and adds properties and methods of its own.


Image source: nnwj.de

Types of inheritance

There are few types of inheritance:

  • Single inheritance, where child classes inherit the features of one and only one parent class.
  • Multiple inheritance, where one class can have more than one superclass and inherit features from all of them.

Also, inheritance can be multilevel, which means a subclass can be inherited from another subclass and so on. And it can be hierarchical, where one class serves as a base class for more than one sub class.

Usually, inheritance in particular language is a mix of two or more types of inheritance. For example in C# it has characteristics of single, multilevel and hierarchical.

Alternative to inheritance is an object composition. In many cases it is preferable alternative.

Short answer

  • Inheritance is one of the four fundamental concepts in OOP.
  • Inheritance is the relationship between two classes where one derives functionality from another and then extends.
  • Inheritance can be single or multiple, multilevel, hierarchical or combination of this types.
  • Object composition is preferable alternative to inheritance in many cases.