Association vs composition vs aggregation

Key takeaways:

  • Association allows objects to relate to each other without ownership.

  • Aggregation represents shared ownership where objects can exist independently.

  • Composition implies strong ownership, binding the lifecycle of contained objects to the parent

Association, composition, and aggregation are fundamental concepts in object-oriented programming (OOP) that define relationships between classes. These relationships play a crucial role in modeling complex systems, as they determine how different parts of a program interact and depend on one another. Understanding these distinctions helps developers create efficient, maintainable, and scalable code.

In OOP, the relationships among classes are often depicted using Unified Modeling Language (UML)https://www.educative.io/answers/what-is-uml, a standardized notation used to visualize software structure. UML diagrams help show relationships like association, aggregation, and composition between classes, offering clarity in system design.

UML notations
UML notations

We’ll dive into these three relationships, exploring each concept with clear examples and code snippets in Java.

Association

An association is a relationship where all objects have their own lifecycle, and there is no owner. It describes how items are related to one another and how they use one another’s functionality. An association can be divided into two types: composition and aggregation. First, let’s understand an association with a scenario.

Consider a school system where teachers and students interact. Many students can associate with a single teacher, and a single student can be associated with multiple teachers. However, there is no ownership between the two objects, and each has its own lifecycle. Both can be created and deleted on their own.

Now, let’s have a look at the UML diagram for this scenario.

Association example in Java

The code below shows a sample implementation of association in the teacher-student scenario as described above.

Teacher.java
Student.java
AssociationTest.java
import java.util.ArrayList;
import java.util.List;
public class AssociationTest {
public static void main(String[] args) {
Teacher teacher1 = new Teacher("Mr. Smith");
Teacher teacher2 = new Teacher("Ms. Johnson");
Student student1 = new Student("Alice");
Student student2 = new Student("Bob");
// Establishing associations
teacher1.addStudent(student1);
teacher1.addStudent(student2);
student1.addTeacher(teacher1);
student1.addTeacher(teacher2);
// Test cases to verify associations
System.out.println("Students of " + teacher1.getName() + ": ");
for (Student s : teacher1.getStudents()) {
System.out.println("- " + s.getName());
}
System.out.println("Teachers of " + student1.getName() + ": ");
for (Teacher t : student1.getTeachers()) {
System.out.println("- " + t.getName());
}
}
}

Code explanation

  • AssociationTest.java

    • Lines 6–10: In the AssociationTest class, Teacher and Student objects are created.

  • Teacher.java

    • Lines 13 and 14: The addStudent() method is used to associate students with their respective teachers. The Teacher class has a private instance variable students, which is a list of Student objects associated with the teacher.

  • Student.java

    • Lines 9 and 10: The addTeacher() method is used to associate teachers with their respective students. The Student class has a private instance variable teachers, which is a list of Teacher objects associated with the student.

Aggregation

Aggregation is a type of association that represents a “has-a” relationship, where one object contains references to others. Aggregation implies a loose ownership, allowing the contained objects to have an independent lifecycle.

Let’s also understand an aggregation with a scenario.
Consider the teacher and their departments as an example. A single teacher cannot belong to more than one department. However, deleting the department does not destroy the teacher's object.

Aggregation example in Java

In a university system, departments aggregate teachers. A teacher belongs to one department, and deleting a department does not delete the teacher. The code below shows a sample implementation of aggregation in the teacher-department scenario as described.

Department.java
Teacher.java
AggregationTest.java
import java.util.ArrayList;
import java.util.List;
public class AggregationTest {
public static void main(String[] args) {
Department department = new Department("Computer Science");
Teacher teacher1 = new Teacher("Dr. Williams");
Teacher teacher2 = new Teacher("Dr. Brown");
// Adding teachers to the department
department.addTeacher(teacher1);
department.addTeacher(teacher2);
// Test cases to verify aggregation
System.out.println("Teachers in " + department.getName() + " Department:");
for (Teacher t : department.getTeachers()) {
System.out.println("- " + t.getName());
}
}
}

Code explanation

  • The Department class has an aggregation relationship with the Teacher class, as it maintains a list of teachers.

  • The addTeacher() method is used to associate a teacher with a department by adding the teacher to the list of teachers.

Composition

Composition is a stronger form of aggregation that represents a whole-part relationship. In composition, the contained objects are strongly owned by the parent, meaning they cannot exist without it. If the parent object is destroyed, all parts it owns are also destroyed. Let’s understand a composition with a scenario:

Consider the link between a house and its rooms. A house can have numerous rooms±no room has an autonomous life, and no single room can belong to two different houses. If we delete the house, the room will be deleted as well. Similarly, another composition relation is between questions and options. A single question can have several answers, and the answers cannot be the same.

Composition example in Java

Consider the relationship between a house and its rooms. A room exists only within a specific house; deleting the house would also remove all its rooms. The code below shows a sample implementation of composition in the house-room scenario as described.

House.java
CompositionTest.java
Room.java
import java.util.ArrayList;
import java.util.List;
class House {
private String address;
private List<Room> rooms;
public House(String address) {
this.address = address;
this.rooms = new ArrayList<>();
}
public void addRoom(int number) {
Room room = new Room(number);
rooms.add(room);
}
public List<Room> getRooms() {
return rooms;
}
public String getAddress() {
return address;
}
}

Code explanation

  • The House class, the rooms attribute is declared as a list of Room objects.

  • The addRoom() method creates a new Room object and adds it to the list of rooms associated with the house.

If you’re preparing for technical interviews, understanding object-oriented programming can be a game changer. Check out our course on Learn Object-Oriented Programming in Java.

Comparison of Association, Aggregation, and Composition


Association

Aggregation

Composition

Relationship

Objects of two classes interact with each other, but have independent lifecycles.


Objects of one class contain a reference to objects of another class.


Objects of one class are composed of objects of another class as integral parts.

Ownership

No ownership or strong dependency.


Shared ownership, where the contained objects can be associated with multiple containers.

Strong ownership, where the contained objects cannot exist independently

Lifecycle


Objects have independent lifecycles and can exist outside of the association.


The contained objects can exist independently and have shared ownership.


The contained objects cannot exist independently and have a lifecycle dependent on the container.

UML representation

Typically represented as a line connecting the related classes.


Represented with a diamond-shaped arrow pointing towards the container class.


Represented with a diamond-shaped arrow pointing towards the container class, accompanied by a solid line.

To further enhance your knowledge and skills in object oriented programming and design, we recommend the Grokking the Low Level Design Interview Using OOD Principles course, which offers interactive lessons that gives hands-on experience with coding problems and opportunities to test and refine your solutions.

Conclusion

In conclusion, understanding the concepts of composition, association, and aggregation is important in object-oriented programming and system modeling. Understanding these relationships helps in accurately modeling and designing software systems. Each relationship type has its own characteristics and implications, allowing for the representation of different dependencies and ownership scenarios

Match The Answer
Select an option from the left-hand side

Consider the relationship between a car and its engine. A car cannot exist without an engine, and an engine cannot be shared among multiple cars.

Composition

In a social media platform, consider the relationship between a user and their friends. A user can have multiple friends, and a friend can be associated with multiple users.

Aggregation

Consider the relationship between a bank and its associated accounts. Each account belongs to only one bank, and a bank can have multiple accounts. If a bank goes bankrupt, all the accounts associated with that bank become inaccessible

Association


Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the primary difference between association, aggregation, and composition?

Association represents a relationship with independent objects, aggregation implies a “has-a” relationship with shared ownership, and composition means strong ownership where contained objects are dependent on the container.


How do I choose between aggregation and composition?

Use aggregation when the child object should exist independently. Use composition when the child object’s lifecycle is tightly bound to the parent.


Can an object be part of multiple associations at the same time?

Yes, an object can be associated with multiple other objects simultaneously in an association. For instance, a student can be associated with multiple teachers, and each teacher can have multiple students.


Are aggregation and composition mutually exclusive?

Yes, an object cannot simultaneously be in both an aggregation and a composition relationship with another object. Aggregation implies shared ownership and independence, while composition implies strict ownership and dependency.


Are these relationships limited to Java, or do they apply to other programming languages?

These relationships are fundamental to OOP and are used in many programming languages, including C++, Python, and C#. The principles are language-agnostic, though the syntax and implementation details vary by language.


Free Resources