Javatpoint Logo
Javatpoint Logo

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.

Composition in Java

Key Points

  • The Composition represents a part-of relationship.
  • Both entities are related to each other in the Composition.
  • The Composition between two entities is done when an object contains a composed object, and the composed object cannot exist without another entity. For example, if a university HAS-A college-lists, then a college is a whole, and college-lists are parts of that university.
  • Favor Composition over Inheritance.
  • If a university is deleted, then all corresponding colleges for that university should be deleted.

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.


Composition in Java

Benefits of using Composition:

  • Composition allows us to reuse the code.
  • In Java, we can use multiple Inheritance by using the composition concept.
  • The Composition provides better test-ability of a class.
  • Composition allows us to easily replace the composed class implementation with a better and improved version.
  • Composition allows us to dynamically change our program's behavior by changing the member objects at run time.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA