Composition vs Inheritance

 It’s big confusing among most of the people that both the concepts are pointing to Code Reusability then what is the difference b/w Inheritance and Composition and when to use Inheritance and when to use Composition? 

Inheritance is used where a class wants to derive the nature of parent class and then modify or extend the functionality of it. Inheritance will extend the functionality with extra features allows overriding of methods, but in the case of Composition, we can only use that class we can not modify or extend the functionality of it. It will not provide extra features. Thus, when one needs to use the class as it without any modification, the composition is recommended and when one needs to change the behavior of the method in another class, then inheritance is recommended.



Inheritance and Composition in Python

This article will compare and highlight the features of is-a relation and has-a relation in Python.

Similar Reads

What is Inheritance (Is-A Relation)?

It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the properties from another class. The class from which the properties and functionalities are utilized is called the parent class (also called as Base Class). The class which uses the properties from another class is called as Child Class (also known as Derived class). Inheritance is also called an Is-A Relation....

What is Composition (Has-A Relation)?

...

Composition vs Inheritance

It is one of the fundamental concepts of Object-Oriented Programming. In this concept, we will describe a class that references to one or more objects of other classes as an Instance variable. Here, by using the class name or by creating the object we can access the members of one class inside another class. It enables creating complex types by combining objects of different classes. It means that a class Composite can contain an object of another class Component. This type of relationship is known as Has-A Relation....

Contact Us