PYTHON

OOPS: Inheritence


Using members of one class inside another class:

We can use members of one class inside another class by using the following ways:-

  1. By Composition (Has-A Relationship)
  2. By Inheritance (IS-A Relationship)

 

By Composition (Has-A Relationship)

  • By using Class Name or by creating object we can access members of one class inside another class is nothing but composition (Has-A Relationship).
  • The main advantage of Has-A Relationship is Code Reusability.
  • Examples:
  • Employee class Has-A Car, hence Employee class can access all members of Car class.
  • Car class Has-A Engine
  • Aero plane class Has-A Tire

 

By Inheritance (is-A Relationship)

  • Whatever variables, methods and constructors available in the parent class by default available to the child classes and we are not required to rewrite.
  • Hence the main advantage of inheritance is Code Reusability and we can extend existing functionality with some more extra functionality.

 

Is-A Relationship

Has-A Relationship

If we want to extend existing functionality with some more extra functionality then we should go for IS-A RelationshipIf we don’t want to extend and just we have to use existing functionality then we should go for HAS-A Relationship

 


 

Types of Inheritance

 

❑ Single Inheritance

The concept of inheriting the properties from one class to another class is known as single inheritance.

 

❑  Multi level Inheritance

The concept of inheriting the properties from multiple classes to single class with the concept of one after another is known as multilevel inheritance.

 

❑  Hierarchical Inheritance

The concept of inheriting properties from one class into multiple classes which are present at same level is known as Hierarchical Inheritance.

 

❑  Multiple Inheritance

The concept of inheriting the properties from multiple classes into a single class at a time, is known as multiple inheritance. If the same method is inherited from both parent classes, then Python will always consider the order of Parent classes in the declaration of the child class.

 

❑  Hybrid Inheritance

Combination of Single, Multi level, multiple and Hierarchical inheritance is known as Hybrid Inheritance.