Composition in Java (original) (raw)

Last Updated : 25 May, 2026

Composition in Java is a design technique used to establish a strong has-a relationship between classes. In composition, one class contains another class, and the contained object cannot exist independently of the container object. It improves flexibility and code reusability by allowing classes to work together instead of relying on inheritance.

Composition is preferred over inheritance in many cases because it provides better flexibility, code reusability, and maintainability.

Features

Composition provides a flexible way to reuse code without using inheritance. It improves maintainability, testability, and allows changing the behavior of a program dynamically at runtime.

Real-Life Example: House and Rooms System

A real-world example of composition is a House and Rooms relationship. The House class manages and contains Room objects internally. Since rooms are created and controlled only by the House object and cannot exist independently in this design, the relationship between them represents composition in Java.

Java `

import java.util.*;

// House class class House {

// Nested Room class
private class Room {

    private String roomName;

    // Constructor
    public Room(String roomName) {
        this.roomName = roomName;
    }

    // Method to display room details
    public void displayRoom() {
        System.out.println("Room : " + roomName);
    }
}

// House contains rooms
private final List<Room> rooms = new ArrayList<>();

// Method to add rooms
public void addRoom(String roomName) {
    rooms.add(new Room(roomName));
}

// Method to display rooms
public void showRooms() {
    for (Room room : rooms) {
        room.displayRoom();
    }
}

}

// Main class class GFG {

public static void main(String[] args) {

    // Creating House object
    House house = new House();

    // Adding rooms
    house.addRoom("Bedroom");
    house.addRoom("Kitchen");
    house.addRoom("Living Room");

    // Displaying rooms
    house.showRooms();
}

}

`

Output

Room : Bedroom Room : Kitchen Room : Living Room

**Explanation: