what is composition in java with example

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: Engine and Car. A Car has an Engine, and if the Car is destroyed, the Engine should be destroyed as well.

Composition example
 * Author: Zameer Ali
 * */
// Engine class
public class Engine {
    private String type;

    public Engine(String type) {
        this.type = type;

    public void start() {
        System.out.println("Engine started");

    // Other methods related to the engine
    // ...

// Car class using composition
public class Car {
    private String model;
    private Engine engine;

    public Car(String model, Engine engine) {
        this.model = model;
        this.engine = engine;

    public void startCar() {
        System.out.println("Car model: " + model);
        System.out.println("Car started");

    // Other methods related to the car
    // ...

// Composition example
public class CompositionExample {
    public static void main(String[] args) {
        // Creating an Engine object
        Engine engine = new Engine("V6");

        // Creating a Car object using composition
        Car car = new Car("Sedan", engine);

        // Starting the car

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.

Leave a Reply

Your email address will not be published. Required fields are marked *