Introduction To Composition in OOPS
Introduction To Composition in OOPS
Composition in OOPS is a fundamental concept and describes a class that refers to one or more objects of the other class instance
variables. It drives the design of the application and lets us know how the application should evolve as there are new features
getting added or any requirements change. It is also one of the specialized but restricted forms of aggregation where two entities
are dependent on each other. In Java, Object-Oriented Programming, it implements has-a relationship, which is achieved by using
an instance variable referring to other objects.
Example:
It is one of the special types of aggregation; restricted aggregation is called composition. This scenario is known as Composition,
when an object contains other objects, and the contained object can’t exist without other objects.
There is no particular syntax for composition, but it is pure programming of the concept.
Code:
private Engine engine; // this shows has – a relationship. (Bike has a Engine)
public Bike() {
engine.setCapacity(250L);
For all Composition examples, the user can control the visibility of other objects to other classes but reuse only what is needed. In
addition, it allows back-end class creation when needed.
So by making use of has – a relationship among classes, known as Composition, we are making the program use instance of the
class directly instead of extending it from other classes, similar to inheritance.
Both entities are dependent on each other, i.e., Bike has – an engine.
If Bike has – an engine, i.e., Entity1 has an Entity2, which means Entity1 is considered as a whole and Entity2 is part of
Entity1. Hence composing objects can’t exist without other objects.
If Bike Entity is deleted, the corresponding Entity2 for the Entity1 has to be deleted.
It has a stronger relationship, represents part of a relationship. For e.g., Hotel has a room. The hotel is a whole, and the room is a
part of it. If Hotel is removed from the relationship, then all the corresponding rooms are to be deleted.
Example #1
Code:
class Car
this.model = model;
this.wheelCount = wheelCount;
class MarutiEngine
class Demo
m.setwheelCount(4);
m.catFeatures();
m.setstartengine();