Java ProgramsOOPComposition

Composition in Java

beginner·  OOP  ·  Relationships

Problem

Composition is the strongest 'has-a' relationship — the contained object is created by, and lives entirely inside, the containing object; it never exists independently.

Model a Library that creates its own Book objects internally, so no Book exists outside of a Library that owns it.

Input
new Library().listBooks()
Output
1984 Brave New World

Java Program

Java
class Book { String title; Book(String title) { this.title = title; } } class Library { private final Book[] books; Library() { // Library creates its own Books — they never exist independently books = new Book[] { new Book("1984"), new Book("Brave New World") }; } void listBooks() { for (Book b : books) { System.out.println(b.title); } } } public class CompositionDemo { public static void main(String[] args) { Library library = new Library(); library.listBooks(); } }

Output

1984 Brave New World

Core Logic

Creating the Book objects directly inside Library's own constructor ties their entire existence to the Library that made them, instead of accepting them from outside.

How It Works
  1. 1Library's constructor calls new Book(...) itself, twice, building both Book objects entirely from within.
  2. 2No Book is ever passed into Library from outside — the caller in main only ever sees a Library, never the Books it contains.
  3. 3listBooks() reads the books array that Library itself populated, printing each title.
  4. 4There is no way to construct one of these particular Book objects without going through Library's constructor first.
Creating new Library() immediately creates both Book objects as a side effect — by the time listBooks() runs, they already exist and were never visible outside the Library.
💡

Key Point: If the Library object were discarded, these particular Book objects would have no other reference keeping them alive — their lifetime is entirely bound to the Library that created them, which is the defining trait of composition.

Key Concepts

compositionownershiphas-a relationship

Related Programs