Inheritance V/S Composition: How to choose?

Inheritance and Composition are two very popular programming techniques of code re-usability . So it is very important to know when to use inheritance over composition and vice versa. Sometimes we tend to over use inheritance when composition can be a better choice. A clear understanding of both can be very useful for code organisation and maintainability.

Now lets start with the definition and then with examples to showcase the difference and use cases.

Inheritance : establishes IS-A relationship. It’s a functionality by which a class acquires the properties and characteristics of another class. It means a class extending another class should be an advanced version of it and thus inherits all the properties of parent class by default. On top of the default features some additional features can be added to the sub class.

Lets understand with an example:

A Dog is an animal.

Here IS-A relationship is established. A dog is a specialized animal with some additional features. So we can clearly use Inheritance here.

Leave a Comment

Your email address will not be published. Required fields are marked *