Inheritance vs. Composition
Learn about inheritance and composition as well as their differences.
We'll cover the following
Code reusability is a fundamental concept in object-oriented programming. We can achieve this by creating relationships between different classes. In this lesson, we will discuss two important concepts that are used for building relationships:
- Inheritance
- Composition
In inheritance, an object acquires the characteristics of one or more (in the case of multiple inheritances) objects. We extend the derived class from the base class. The derived class inherits the features that are in the base class. The derived class can add features of its own as well.
Inheritance is an is-a relationship. For example, a car is a vehicle. Apple is a fruit.
In composition, the object of one class becomes a member of another class. It is known as the has-a relationship in object-oriented programming. For example, a car has-a engine, a car has-a steering. In composition, we have a reference variable to the object of another class or classes. For example, the car class can have a variable reference to the object of an engine class or steering class or to both of them.
Get hands-on with 1400+ tech skills courses.