OOP.What is the difference between composition and aggregation?

This is one of the most common areas of confusion when learning about object-oriented relationships. Let me break it down for you in a clear and practical way.


🛠️ Both are “has-a” Relationships

Both composition and aggregation describe a “has-a” relationship between two classes — meaning one class contains or owns another class. The difference is the strength and nature of ownership.


📦 1️⃣ Composition (Strong Ownership)

What is Composition?

  • One object is a part of another object.
  • The child object’s lifecycle is fully dependent on the parent.
  • If the parent dies, the child dies too.
  • Tight coupling between parent and child.

Real-World Example

A Car has an Engine.

  • The engine cannot exist independently — it’s part of the car.
  • When you destroy the car, the engine is gone too.

Code Example

class Engine {
    void start() { System.out.println("Engine started"); }
}

class Car {
    private final Engine engine;

    public Car() {
        this.engine = new Engine(); // Car creates its own engine
    }

    public void start() {
        engine.start();
        System.out.println("Car started");
    }
}

Car owns and manages the Engine — strong lifecycle dependency.


🏘️ 2️⃣ Aggregation (Weak Ownership)

What is Aggregation?

  • One object has a reference to another object.
  • The child object can exist independently of the parent.
  • If the parent dies, the child can continue to exist.
  • Looser coupling than composition.

Real-World Example

A Library has Books.

  • The books exist independently — they aren’t destroyed if the library closes.
  • Books can also belong to other libraries.

Code Example

class Book {
    String title;
    public Book(String title) { this.title = title; }
}

class Library {
    private List<Book> books;

    public Library(List<Book> books) {
        this.books = books; // Library gets books from outside
    }
}

Library aggregates Book, but does not own their lifecycle — books can exist without the library.


🔥 Quick Comparison Table

AspectCompositionAggregation
OwnershipStrong (parent owns child fully)Weak (parent just holds reference)
LifecycleParent & child live/die togetherChild can outlive parent
ExampleCar & EngineLibrary & Book
Object CreationParent usually creates the childChild is created outside and passed in
CouplingTighterLooser

💡 Rule of Thumb

QuestionWhich to use?
Does the part only exist inside the whole?Use composition.
Can the part exist independently and be reused elsewhere?Use aggregation.
This entry was posted in Без рубрики. Bookmark the permalink.