Composition
In this lesson, you'll learn how to achieve composition in Java.
We'll cover the following
Composition
is the practice of creating other class objects in your class. In such a scenario, the class which creates the object of the other class is known as the owner and is responsible for the lifetime of that object.
Composition relationships are Part-of relationships where the part must constitute part of the whole object. We can achieve composition by adding smaller parts of other classes to make a complex unit.
So, what makes the composition so unique?
In composition, the lifetime of the owned object depends on the lifetime of the owner.
Example
A car
is composed of an engine, tires, and doors. In this case, a Car
owns these objects so a Car
is an Owner class and tires
,doors
and engine
classes are Owned classes.
Get hands-on with 1400+ tech skills courses.