Java ProgramsOOPAggregation

Aggregation in Java

beginner·  OOP  ·  Relationships

Problem

Aggregation is a weaker 'has-a' relationship than composition — the contained object exists on its own, and the containing object merely holds a reference to it.

Model a Library that holds a set of Book objects that were created independently, outside the Library itself.

Input
new Library(books).listBooks(), where books already existed beforehand
Output
1984 Brave New World

Java Program

Java
class Book { String title; Book(String title) { this.title = title; } } class Library { private final Book[] books; // Books already exist — Library only stores a reference to them Library(Book[] books) { this.books = books; } void listBooks() { for (Book b : books) { System.out.println(b.title); } } } public class AggregationDemo { public static void main(String[] args) { Book[] books = { new Book("1984"), new Book("Brave New World") }; Library library = new Library(books); library.listBooks(); } }

Output

1984 Brave New World

Core Logic

Building the Book array in main first, then passing it into Library's constructor, means the Books' existence never depended on the Library at all.

How It Works
  1. 1Book[] books = { new Book("1984"), new Book("Brave New World") }; creates both books in main, before any Library exists.
  2. 2Library's constructor just stores the array it's handed — it doesn't create a single Book itself.
  3. 3new Library(books) hands that already-built array over, so Library starts out merely referencing objects that already existed.
  4. 4listBooks() reads the same array reference, printing each title exactly as composition's version does.
The Book objects are fully constructed in main before Library is even created — by the time new Library(books) runs, it's just being handed a reference to objects that already exist.
💡

Key Point: Unlike composition, discarding this Library object wouldn't affect the Book objects at all — they were created independently in main and would keep existing as long as anything else still refers to them.

Key Concepts

aggregationshared referencehas-a relationship

Related Programs