What is composition in object oriented programming?

What is composition?

Composition is a design pattern in object-oriented programming (OOP) that establishes a “has-a” relationship between objects. This means that one object, called the container, contains another object, called the contained object.

Example of composition:

// Example of Composition

// The Engine class represents a component that can be part of a Car
class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

// The Car class uses composition by containing an instance of the Engine class
class Car {
    private Engine engine; // Composition: Car "has" an Engine

    public Car() {
        this.engine = new Engine(); // Initialize the Engine when creating a Car
    }

    public void startCar() {
        engine.start(); // Delegate the start functionality to the Engine
        System.out.println("Car started");
    }
}

In this example, the Car class has a field of type Engine, establishing a “has-a” relationship through composition. The Car class doesn’t inherit from the Engine class but uses an instance of Engine to utilize its functionality.

Composition allows better flexibility as the Car can have other parts and functionalities aside from the Engine, and it’s not tightly bound to the implementation details of the Engine class.

Benefits of Composition:

Composition offers several advantages over other design patterns, such as inheritance:

  • Flexibility: Composition allows for greater flexibility in object relationships, as objects can be easily added or removed from the composition.
  • Reusability: Composition promotes code reusability by allowing the reuse of existing classes within different structures.
  • Decoupling: Composition reduces coupling between classes, as the contained objects are independent and can be changed or replaced without affecting the container.

Key Differences between Composition and Inheritance

Inheritance and composition are both design patterns that establish relationships between classes. However, they differ in their nature and implementation:

FeatureCompositionInheritance
Relationship type
FlexibilityMore flexibleLess flexible
CouplingLower couplingHigher coupling
Code reusePromotes code reuseRelies on code reuse from parent class
ExampleAPersonclass with aCarobjectADogclass derived from aMammalclass