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.
- Represents a strong dependency between objects.
- Objects are created and managed by the owner class.
- Provides better maintainability and flexibility in applications.
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.
- Supports code reusability and flexibility.
- Helps achieve multiple inheritance-like behavior in Java.
- Improves testability and maintainability of classes.
- Allows replacing or modifying member objects easily.
- Enables dynamic behavior changes 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.
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:
Roomobjects are created and managed only by the House class.- A Room cannot exist independently outside the House.
- This represents a strong has-a relationship, which is composition in Java