Composition in Java
The Composition is a way to design or implement the "has-a" relationship. Composition and Inheritance both are design techniques. The Inheritance is used to implement the "is-a" relationship. The "has-a" relationship is used to ensure the code reusability in our program. In Composition, we use an instance variable that refers to another object.
The composition relationship of two objects is possible when one object contains another object, and that object is fully dependent on it. The contained object should not exist without the existence of its parent object. In a simple way, we can say it is a technique through which we can describe the reference between two or more classes. And for that, we use the instance variable, which should be created before it is used.
Let's take an example of a university and its colleges to understand the concept of Composition.
We create a class College that contains variables, i.e., name and address. We also create a class University that has a reference to refer to the list of colleges. A University can have more than one collages. So, if a university is permanently closed, then all colleges within that particular university will be closed because colleges cannot exist without a university. The relationship between the university and colleges is Composition.
Benefits of using Composition: