Java Composition

Introduction

Composition is one of the most important concepts in Object-Oriented Programming (OOP) in Java. It represents a strong “has-a” relationship between two classes, where one object owns another object. Unlike Aggregation, where the child object can exist independently, Composition establishes a strong ownership relationship in which the child object’s lifecycle depends entirely on the parent object.

Composition helps developers model real-world relationships where one object is an essential part of another. For example, a House consists of Rooms, a Car consists of an Engine, and a Human has a Heart. If the parent object no longer exists, the child object also ceases to exist because it cannot function independently.

In Java, composition is commonly achieved by creating objects of one class inside another class. The parent class is responsible for creating and managing the child object’s lifecycle.

One of the most famous software engineering principles is:

Favor Composition Over Inheritance

This principle encourages developers to build flexible applications by combining objects rather than relying heavily on inheritance.

What is Composition?

Composition is a relationship where one class owns another class, and the child object cannot exist independently of the parent object.

It represents a strong ownership relationship.

Definition:

Composition is a strong “has-a” relationship in which the parent object owns the child object, and the child’s lifecycle depends on the parent.

Examples include:

  • House → Room
  • Car → Engine
  • Human → Heart
  • Computer → Motherboard
  • Book → Chapters

If the parent object is destroyed, the child object is also destroyed.

Why Do We Need Composition?

Without composition, classes often become tightly coupled through inheritance or contain responsibilities that do not naturally belong together.

Composition provides:

  • Better code organization
  • Reusable components
  • Strong ownership modeling
  • Easier maintenance
  • Clear object responsibilities

It is ideal when one object is an integral part of another.

Syntax

Composition is usually implemented by creating and managing the child object inside the parent class.


class Engine {
}
class Car {
    private Engine engine = new Engine();
}

Here, the Car creates and owns its Engine. The Engine lifecycle is tied to the Car.

Basic Example of Composition


class Engine {
    void start() {
        System.out.println("Engine Started")
}
class Car {
    private Engine engine;
    Car() {
        engine = new Engine();
    }
    void startCar() {
        engine.start();
        System.out.println("Car Started");
    }
}
public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.startCar();
    }
}

Output

Engine Started Car Started

The Engine object is created inside the Car, demonstrating strong ownership.

How Composition Works

The parent object creates and manages the child object.


Car
 │
 ├── Creates
 ▼
Engine

The child object cannot meaningfully exist without the parent object in this relationship.

Features of Composition

Composition has the following characteristics:

  • Represents a strong has-a relationship.
  • Parent owns the child object.
  • Child lifecycle depends on the parent.
  • Promotes encapsulation.
  • Encourages modular design.
  • Improves code reusability.
  • Reduces unnecessary inheritance.
  • Helps build flexible applications.

Real-Life Example

Consider a House and its Rooms.


class Room {
    void open() {
        System.out.println("Room Opened");
    }
}
class House {
    private Room room
    House() {
        room = new Room();
    }
    void enterHouse() {
        room.open();
System.out.println("Entered House");
    }
}
public class Main {
    public static void main(String[] args) {
        House house = new House();
        house.enterHouse();
    }
}

Output

Room Opened
Entered House

The House owns the Room, and the room’s lifecycle is managed by the house.

Composition with Multiple Objects

A parent class may own multiple child objects.

Example:


import java.util.ArrayList;
import java.util.List;
class Chapter {
    String title;
    Chapter(String title) {
        this.title = title;
    }
}
class Book {
    private List chapters = new ArrayList();
    void addChapter(String title) {
        chapters.add(new Chapter(title));
    }
    void displayChapters() {
        for (Chapter chapter : chapters) {
            System.out.println(chapter.title);
        }
    }
}

Here, the Book creates and owns all Chapter objects.

Composition vs Aggregation

Composition Aggregation
Strong ownership Weak ownership
Child depends on parent Child exists independently
Parent creates or owns child Parent references child
Child lifecycle depends on parent Child lifecycle is independent
Example: Car–Engine Example: Department–Employee

Composition vs Inheritance

Composition Inheritance
Represents a has-a relationship Represents an is-a relationship
Combines objects Extends classes
More flexible More rigid
Supports loose coupling Can create tight coupling if overused
Encouraged for reusable design Useful only for genuine inheritance hierarchies

Remember the popular object-oriented design principle:


Favor Composition Over Inheritance

Composition often leads to more maintainable and extensible software.

Advantages of Composition

Composition offers several benefits:

  • Models strong ownership relationships accurately.
  • Promotes encapsulation.
  • Improves code reuse through object collaboration.
  • Reduces unnecessary inheritance.
  • Makes applications easier to maintain.
  • Encourages modular architecture.
  • Simplifies testing of individual components.
  • Supports flexible software design.

Best Practices

Follow these best practices when using composition:

📖
Best Practices:
  • Use composition when one object is an essential part of another.
  • Create child objects inside the parent only when ownership is required.
  • Keep object responsibilities clearly separated.
  • Prefer composition over inheritance unless there is a true is-a relationship.
  • Hide child objects using encapsulation where appropriate.
  • Avoid exposing internal implementation details unnecessarily.
  • Keep classes focused on a single responsibility.

Common Mistakes

Beginners often make these mistakes:

  • Confusing composition with aggregation.
  • Using inheritance where composition is more appropriate.
  • Allowing externally managed objects in situations requiring strong ownership.
  • Creating unnecessary deep object hierarchies.
  • Ignoring lifecycle dependency between parent and child.
  • Overcomplicating simple object relationships.
  • Exposing internal child objects directly.

Conclusion

Java Composition is a powerful object-oriented relationship that represents a strong “has-a” relationship between objects. In composition, the parent object owns and manages the child object, making their lifecycles closely connected. This accurately models many real-world relationships, such as cars and engines, houses and rooms, or books and chapters.

Composition promotes encapsulation, modularity, and code reusability, making applications more flexible and maintainable. Combined with the widely accepted principle “Favor Composition Over Inheritance,” it encourages developers to build software by combining specialized objects instead of relying on deep inheritance hierarchies. Understanding composition is essential for mastering object-oriented design and creating scalable Java applications.

Related Java Tutorials