• ↑↓ to navigate
  • ↵ to open
  • ⟶ to select
  • ⌘ ⌥ ↵ to open in a panel
  • ←→ to navigate
  • esc to dismiss
⌘ '
keyboard shortcuts

What’s Being Compared

Two forms of association in Java: Aggregation (weak “has-a”) and Composition (strong “has-a”). Both represent whole-part relationships but differ fundamentally in lifecycle dependency and ownership semantics.

The Core Tension

The key question is: who owns the lifecycle? In aggregation, parts can outlive the whole. In composition, the whole owns the parts completely — when the whole dies, the parts die with it. Choosing wrong creates either memory leaks (too strong) or premature destruction (too weak).

Comparison

DimensionAggregationComposition
Relationship strengthWeakStrong
Lifecycle dependencyIndependentDependent
OwnershipShared (multiple containers can share)Exclusive (one owner)
Object creationCreated externally, passed inCreated inside container constructor
UML notationHollow diamondFilled diamond
ExampleCompany has EmployeesHouse has Rooms
Part survival after container deathSurvivesDies with container
Memory implicationPart may remain reachablePart becomes unreachable
Code patternclass Company { List<Employee> employees; }class House { List<Room> rooms = new ArrayList<>(); }

When to Choose Aggregation

  • Parts have independent existence (Employees, Students, Customers)
  • Parts are shared across multiple containers (a Student in multiple Courses)
  • The container is a temporary grouping, not a parent

When to Choose Composition

  • Parts have no meaning outside the container (Rooms of a House, Pages of a Book)
  • Exclusive ownership is required (a BankAccount’s TransactionHistory)
  • Lifecycle management should be automatic (create part with container, destroy with container)

The Insight

The distinction is fundamentally about lifecycle responsibility. Aggregation transfers the lifecycle burden to external code (someone else must create and destroy the parts). Composition internalizes it (the container manages everything). This has real consequences: aggregation is more flexible but can cause memory leaks if parts aren’t cleaned up; composition is safer but less reusable.

Visual Explanation

java_aggregation_vs_composition A Java Aggregation Vs Input B Java Aggregation Vs Core Mechanism A->B triggers C Java Aggregation Vs Output B->C produces

Semantic Network

semantic_java_aggregation_vs_composition THIS Java Aggregation Vs REL1 Related Concept THIS--REL1 related REL2 Builds Into THIS--REL2 builds into

Connections

  • Aggregation — weak association with independent lifecycles
  • Composition — strong association with dependent lifecycles
  • Association — the parent concept of both
  • Encapsulation — both rely on encapsulation to manage internal state