Composition

In Java, composition is a design principle that allows you to create complex objects by combining simpler objects or types. It is a way to achieve code reuse without using inheritance. Composition involves creating relationships between classes by having one class contain an instance of another class. This is in contrast to inheritance, where a class can inherit properties and behaviors from another class.

Here's a simple example to illustrate composition in Java:

// Simple class representing an Engine
class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

// Class representing a Car that uses composition to include an Engine
class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public void start() {
        System.out.println("Car is starting");
        engine.start();
    }
}

public class CompositionExample {
    public static void main(String[] args) {
        // Create an Engine instance
        Engine carEngine = new Engine();

        // Create a Car instance, passing the Engine instance through the constructor
        Car myCar = new Car(carEngine);

        // Start the car, which internally starts the engine
        myCar.start();
    }
}

In this example:

  • The Engine class has a method start() that prints a message indicating the engine is starting.

  • The Car class has a composition relationship with the Engine class. It contains an instance of the Engine class as a private member variable.

  • The Car class also has a method start(), which, in addition to printing a message for the car starting, delegates the task of starting the engine to the Engine instance.

By using composition, you can create modular and flexible code. If you later need to change the behavior of the Engine class, it won't affect the Car class as long as the interface between them remains the same. This is in contrast to inheritance, where changes to a superclass can potentially affect all subclasses.

Example 2

Credits: https://www.geeksforgeeks.org/composition-in-java/

Last updated

Was this helpful?