Composition in JavaLast Updated : 7 Jan 2026 Composition and inheritance both are design techniques. The Composition is a way to design or implement the "has-a" relationship while inheritance is used to implement the "is-a" relationship. It 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. It represents a strong association, if the parent object is destroyed, the contained object also ceases to exist. ![]() Important points to Remember
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. ExampleCompile and RunOutput: Name: ABES Engineering College and Address: Ghaziabad Name: AKG Engineering College and Address: Ghaziabad Name: ACN College of Engineering & Management Studies and Address: Aligarh Advantages of Composition
When to Use Composition?We should use composition in the following cases:
Composition Vs. Inheritance
Next TopicCharbuffer-hasarray-method-in-java |
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India
