Understanding Association, Aggregation, and Composition in Java

Objects and Classes are the foundation of object-oriented programming in Java. These concepts help us effectively design our own software applications. In complex applications, we often encounter scenarios where objects of different classes need to interact with each other. 

To manage these interactions, we use various kinds of relationships between classes. The main three key relationships in Java are: 

Association: Association describes the relationships or connections between various objects. It represents a general relationship between objects without any strong dependency.

Aggregation: Aggregation is a specific type of association that represents a “has-a” relationship. It means one object is composed of or contains another object. The contained object can exist independently or be part of multiple containers.

Composition: Composition is a stronger version of aggregation. In this relationship, one object is made of or composed of another object. The composed object is closely related to and reliant on the container object for its very survival. 

It is to be mentioned that composed objects are also destroyed when the container is destroyed. A composed object cannot exist independently.

However, having a clear understanding of these relationships is crucial in designing complex software applications in Java. Each relationship offers a different level of dependency and ownership between classes, allowing developers to model real-world scenarios effectively. 

In this article, we will take you through the major differences between all three dependency levels in Java and their importance.

Recommended Course 

Association In Object-Oriented Programming 

Association is a way to establish a relationship between two separate classes by using their objects. It promotes class communication and allows them to collaborate on specific goals or purposes. Consider it as a connection or link that enables interaction between two classes.

Types of Association

Let us look into the types of Association and their role in object-oriented programming.

One-to-One Association

This type of association describes a situation where one object is associated with only one other object and vice versa. It resembles a particular and exclusive connection between two things.

Example: Each student has only one unique student ID card in a school system, which is a type of one-to-one association.

One-to-One Association 
class Student {

       String name;

        int studentId;

   

   Student (String name, int studentId) {

        this.name = name;

        this.studentId = studentId;

    }

}

class StudentIDCard {

      int card_Number;

      Student owner;

  StudentIDCard (int cardNumber, Student owner) {

   this.cardNumber = cardNumber;

    this.owner = owner;

    }

}

One-to-Many Association

In a one-to-many association, one object is associated with multiple objects of another class, but each of those objects is related to only one instance of the first class.

Example: A teacher at the school teaches various subjects to various students, implying a one-to-many association between the teacher and the students.

One-to-Many Association 
class Teacher {

       String name;

       String subject;

    

  Teacher (string name, String subject) {

        this.name = name;

        this.subject = subject;

    }

}

class Student {

      String name;

      Teacher teacher;

    

   Student (String name, Teacher teacher) {

        this.name = name;

        this.teacher = teacher;

    }

}

 

  • Many-to-One Association

The opposite of a one-to-many association is a many-to-one association. Here, one object from one class is linked to several objects from another class. 

Example: Consider an employee in an office who has to interact with multiple departments, such as finance, human resources, and management. 

Example: Consider a school with multiple classes, and in each class, many students are studying together. This is a Many-to-one association.

Many-to-One Association 
class SchoolClass {

      String className;

      List<Student> students;

SchoolClass (String className) {

      this.className = className;

      students = new ArrayList<>();

    }

void addStudent (Student student) {

     students.add(student);

    }

}

class Student {

      String name;

      SchoolClass schoolClass;

Student (String name, SchoolClass schoolClass) {

      this.name = name;

      this.schoolClass = schoolClass;

    }

}

Many-to-Many Association

Multiple objects from one class are related to multiple objects from another class in a many-to-many association. It resembles a connection between two groups of entities that is many-to-many.

Example: There are many extracurricular activities that students in the school take part in, and each activity includes several students. This example depicts the many-to-many association, as all the students are linked to many activities happening in school.

Many-to-Many Association 
class Student {

    String name;

    List<Activity> activities;

    

    Student (String name) {

        this.name = name;

        activities = new ArrayList<>();

    }

    

    void addActivity(Activity activity) {

        activities.add(activity);

    }

}

class Activity {

    String activityName;

    List<Student> participants;

    

    Activity(String activityName) {

        this.activityName = activityName;

        participants = new ArrayList<>();

    }

    

    void addParticipant (Student student) {

        participants.add(student);

    }

}

Aggregation In Object-Oriented Programming

In Java, an Aggregation is a particular kind of connection between two classes. This connection between two or more entities is shown as a “has-a” relationship. In this relationship, one class contains a reference to another class and is considered independent of the other. If one class object is deleted, it does not affect the other class object.

Let us clearly understand this with an example. Consider a Library named PhysicsWallah and a Book. There are many books in the library, and each one is the property of the library. It does not necessarily mean the library is destroyed if a book is returned or removed. The Book and the Library have a  “has-a” relationship.

In this example, the Library is the Aggregate class, which contains references to many Book objects considered parts of the Library. The Library is responsible for managing the collection of books, but the existence of a book does not depend on the Library.

Aggregation In Object-Oriented Programming
class Book {

    String title;

    String author;

    Book (String title, String author) {

        this.title = title;

        this.author = author;

    }

}

class Library {

    String name;

    List<Book> books;

    Library (String name) {

        this.name = name;

        books = new ArrayList<>();

    }

    void addBook(Book book) {

        books.add(book);

    }

    void removeBook(Book book) {

        books.remove(book);

    }

    List<Book> getAllBooks() {

        return books;

    }

}

public class LibraryExample {

    public static void main(String[] args) {

// Creating a Library and some Book objects

        Library library = new Library (“PhysicsWallah Library”);

        Book book1 = new Book (“Harry Potter and the Sorcerer’s Stone”, “J.K.    Rowling”);

        Book book2 = new Book (“To Kill a Mockingbird”, “Harper Lee”);

        // Adding books to the Library

        library.addBook(book1);

        library.addBook(book2);

// Printing all books in the Library

        System.out.println(“Books in ” + library.name + “:”);

        for (Book book : library.getAllBooks()) {

            System.out.println(“Title: ” + book.title + “, Author: ” + book.author);

        }

 // Removing a book from the Library

        library.removeBook (book2);

// Printing updated list of books in the Library

        System.out.println (“Books in ” + library.name + ” after removing a book:”);

        for (Book book : library.getAllBooks()) {

            System.out.println (“Title: ” + book.title + “, Author: ” + book.author);

        }

    }

}

 

Output:

Output
Books in PhysicsWallah Library:

Title: Harry Potter and the Sorcerer’s Stone, Author: J.K. Rowling

Title: To Kill a Mockingbird, Author: Harper Lee

Books in PhysicsWallah Library after removing a book:

Title: Harry Potter and the Sorcerer’s Stone, Author: J.K. Rowling

Composition In Object-Oriented Programming 

Composition in Java is a type of relationship between classes that shows a strong connection or association. It is also referred to as “Belongs-To association”. The composite object cannot exist independently on its own, unlike association relationship.

This is also referred to as Strong Association because one class essentially belongs to another class and relies on it for its existence. In simpler words, it means that one class is part of another and cannot exist independently.

Imagine we are building a simple house designing application in Java. This application has two classes: “House” and “Room”. The House class represents the larger class, and the Room class represents the smaller class.

Here, the House “has” rooms, meaning the House class contains objects of the Room class. Each house can have multiple rooms, such as bedrooms, living rooms, and bathrooms.

Let us establish a composition relationship for this scenario given above.

Composition In Object-Oriented Programming
// One house room is represented by the Room class.

class Room {

// Room properties and methods

}

// The House class represents the entire house and includes spaces

class House {

    private Room livingRoom;    

    private Room bedroom; 

    private Room bathroom; 

// House properties and methods

}

In this example, the House class cannot exist independently without its rooms. As the living room, bedroom, and bathroom are all essential components of the House.

It follows logically that the living room, bedroom, and bathroom cannot exist independently if the House class is eliminated.

The composition relationship in this instance shows a close relationship between the House and Room classes. The rooms are essential to the proper operation of the House class.

FREQUENTLY ASKED QUESTIONS (FAQs)

Q1. What is Association in object-oriented programming?

Ans: In object-oriented programming, association denotes a general relationship between two classes that is devoid of any significant dependencies. It promotes group communication and allows students to work together on particular objectives.

Q2. What are the different types of Association in Java?

Ans: There are main four types of Association in Java namely.

  • One-to-One Association
  • One-to-Many Association
  • Many-to-One Association
  • Many-to-Many Association

You can find a brief explanation of these relationships in this article above.

Q3. How does Aggregation differ from Association in Java?

Ans: Aggregation is a specific type of Association that represents a “has-a” relationship. In Aggregation, a class can refer to another class while the object it contains can exist independently or as a component of multiple containers. 

Association, on the other hand, represents a weakly dependent general connection between classes.

Q4. What is Composition in Java, and how does it differ from Aggregation?

Ans: Composition is a stronger version of Aggregation. In Composition, one class is made up of or composed of another class. 

The composed object is closely related to and dependent on the container object for its existence. If the container is destroyed, the composed object is also destroyed. In Aggregation, the contained object can exist independently.

Recommended Reads

Data Science Interview Questions and Answers

Data Science Internship Programs 

Master in Data Science

IIT Madras Data Science Course 

BSC Data Science Syllabus 

Telegram Group Join Now
WhatsApp Channel Join Now
YouTube Channel Subscribe
Scroll to Top
close
counselling
Want to Enrol in PW Skills Courses
Connect with our experts to get a free counselling & get all your doubt cleared.