DEV Community

Cover image for Inheritance Vs Composition
Cesar Bermudez
Cesar Bermudez

Posted on

Inheritance Vs Composition

Hi everybody 😊,

Let’s talk about inheritance vs composition

They are key concepts in OOP, both are mechanism to reuse code and class hierarchy, but they have different approaches and they are use in different context

Inheritance

It’s allows to create a class and reuse codes, we create a father class which has all the implementation of its own method, we can extends the class to another class, this class is a child from the class that is extends, but the child class can have extra methods and attributes, you can also override the father methods if you need an specific implementation of that method.

  • It’s a mechanism through which a class can inherit attributes and methods from another class.

  • The class inherits characteristics from another class.
    The sub-class can add methods and attributes and override a method which comes from the superclass.

Example

A class name “Dog” can inherit from a class name “Animal”. The class Dog inherits attributes and methods from Animal as name and the method to eat, but also it could have their own methods and attributes, such as breed.

Inhericante example

Composition

It’s the design technique in OOP to implement has-a relationship between objects, it’s very useful designing software components, at the beginning it could be challenging, because an object contains one or more objects from another class as part of its structure, when using this concept you can:

  • Reuse existing code, It’s allows you to reuse code with modeling association as you do in inheritance, that’s allows to encapsulate and makes your code more easier to maintain, as you can see is very use in real world, for example a car is not an engine, it’s a composition of many differents components unit via externals API’s to compose a higher level of abstraction and provide more significant use value to their users.

  • The objects contains are not expose directly to external classes, for that reason could be changed, but it not an instance of a concrete class

Example

A class named Car could has a class name Engine as part of its structure, the Car has a Engine, but the Engine it’s not a special type of Car

Composition example

Summary

Inheritance is used for modeling hierarchical relationships between classes, while composition is used to build complex objects combining other objects.
Both are important in OOP and they are used depending on design's necessity and the nature of the relationships between classes in the system.

Top comments (0)