what is composition in java with example
Composition is a strong form of association in Java where one class contains an object of another class. In other words, it’s a relationship in which one class is composed of one or more objects of other classes. The composed objects have their lifecycle tightly coupled to the lifecycle of the container class. If the container class is destroyed, all the composed objects are destroyed as well. Composition represents a “has-a” relationship and is a way to create more complex classes using simpler, smaller classes.
Here’s an example to illustrate composition in Java:
Let’s consider two classes:
Car has an
Engine, and if the
Car is destroyed, the
Engine should be destroyed as well.
In this example, the
Car class contains an
Engine object. The
Car class and the
Engine class are independent entities, but a
Car is composed of an
Engine. If you create a
Car object, it must have an associated
Engine object. If the
Car object is destroyed, the
Engine object associated with it will also be destroyed.
Composition allows you to create complex objects by combining simpler objects, promoting code reusability, and making it easier to maintain and understand the codebase.