Skip to content
Related Articles

Related Articles

Difference Between Aggregation and Composition in Java

Improve Article
Save Article
  • Last Updated : 09 Jun, 2022
Improve Article
Save Article

Aggregation and composition describe the type of relationships between objects when communicating with each other, this might be used in low-level design to depict associations between objects. In this article, we are going to discuss the differences between Aggregation and Composition in Java programming language. 

Aggregation

It is a special form of Association where:

  • It represents Has-A’s relationship.
  • It is a unidirectional association i.e. a one-way relationship. For example, a department can have students but vice versa is not possible and thus unidirectional in nature.
  • In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.
Example of Aggregation in Java

 

Example:

Java




// Java program to illustrate the 
// Concept of Aggregation
  
// Importing required classes
import java.io.*;
import java.util.*;
  
// Class 1
// Student class
class Student {
  
    // Attributes of student
    String name;
    int id;
    String dept;
  
    // Constructor of student class
    Student(String name, int id, String dept)
    {
  
        // This keyword refers to current instance itself
        this.name = name;
        this.id = id;
        this.dept = dept;
    }
}
  
// Class 2
// Department class contains list of student objects
// It is associated with student class through its Objects
class Department {
    // Attributes of Department class
    String name;
    private List<Student> students;
    Department(String name, List<Student> students)
    {
        // this keyword refers to current instance itself
        this.name = name;
        this.students = students;
    }
  
    // Method of Department class
    public List<Student> getStudents()
    {
        // Returning list of user defined type
        // Student type
        return students;
    }
}
  
// Class 3
// Institute class contains list of Department
// Objects. It is associated with Department
// class through its Objects
class Institute {
  
    // Attributes of Institute
    String instituteName;
    private List<Department> departments;
  
    // Constructor of institute class
    Institute(String instituteName,List<Department> departments)
    {
        // This keyword refers to current instance itself
        this.instituteName = instituteName;
        this.departments = departments;
    }
  
    // Method of Institute class
    // Counting total students of all departments
    // in a given institute
    public int getTotalStudentsInInstitute()
    {
        int noOfStudents = 0;
        List<Student> students;
  
        for (Department dept : departments) {
            students = dept.getStudents();
  
            for (Student s : students) {
                noOfStudents++;
            }
        }
  
        return noOfStudents;
    }
}
  
// Class 4
// main class
class GFG {
  
    // main driver method
    public static void main(String[] args)
    {
        // Creating object of Student class inside main()
        Student s1 = new Student("Mia", 1, "CSE");
        Student s2 = new Student("Priya", 2, "CSE");
        Student s3 = new Student("John", 1, "EE");
        Student s4 = new Student("Rahul", 2, "EE");
  
        // Creating a List of CSE Students
        List<Student> cse_students = new ArrayList<Student>();
  
        // Adding CSE students
        cse_students.add(s1);
        cse_students.add(s2);
  
        // Creating a List of EE Students
        List<Student> ee_students
            = new ArrayList<Student>();
  
        // Adding EE students
        ee_students.add(s3);
        ee_students.add(s4);
  
        // Creating objects of EE and CSE class inside
        // main()
        Department CSE = new Department("CSE", cse_students);
        Department EE = new Department("EE", ee_students);
  
        List<Department> departments = new ArrayList<Department>();
        departments.add(CSE);
        departments.add(EE);
  
        // Lastly creating an instance of Institute
        Institute institute = new Institute("BITS", departments);
  
        // Display message for better readability
        System.out.print("Total students in institute: ");
  
        // Calling method to get total number of students
        // in institute and printing on console
        System.out.print(institute.getTotalStudentsInInstitute());
    }
}


Output:

Total students in institute: 4

Output Explanation: In this example, there is an Institute that has a number of departments like CSE and EE. Every department has no. of students. So, we make an Institute class that has a reference to Object or no. of Objects (i.e. List of Objects) of the Department class. That means the Institute class is associated with the Department class through its Object(s). And Department class has also a reference to Objects or Objects (i.e. List of Objects) of the Student class means it is associated with the Student class through its Object(s). It represents a Has-A relationship. In the above example: Student Has-A name. Student Has-A ID. Student Has-A Dept. Department Has-A Students as depicted from the below media. 

 

When do we use Aggregation ?? 

Code reuse is best achieved by aggregation.  

Composition 

Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.  

  • It represents part-of relationship.
  • In composition, both entities are dependent on each other.
  • When there is a composition between two entities, the composed object cannot exist without the other entity.

 

Example:

Java




// Java program to illustrate
// the concept of Composition
  
// Importing required classes
import java.io.*;
import java.util.*;
  
// Class 1
// Book
class Book {
  
    // Attributes of book
    public String title;
    public String author;
  
    // Constructor of Book class
    Book(String title, String author)
    {
  
        // This keyword refers to current instance itself
        this.title = title;
        this.author = author;
    }
}
  
// Class 2
class Library {
  
    // Reference to refer to list of books
    private final List<Book> books;
  
    // Library class contains list of books
    Library(List<Book> books)
    {
  
        // Referring to same book as
        // this keyword refers to same instance itself
        this.books = books;
    }
  
    // Method
    // To get total number of books in library
    public List<Book> getTotalBooksInLibrary()
    {
  
        return books;
    }
}
  
// Class 3
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating objects of Book class inside main()
        // method Custom inputs
        Book b1
            = new Book("EffectiveJ Java", "Joshua Bloch");
        Book b2
            = new Book("Thinking in Java", "Bruce Eckel");
        Book b3 = new Book("Java: The Complete Reference",
                        "Herbert Schildt");
  
        // Creating the list which contains number of books
        List<Book> books = new ArrayList<Book>();
  
        // Adding books
        // using add() method
        books.add(b1);
        books.add(b2);
        books.add(b3);
  
        Library library = new Library(books);
  
        // Calling method to get total books in library
        // and storing it in list of user0defined type -
        // Books
        List<Book> bks = library.getTotalBooksInLibrary();
  
        // Iterating over books using for each loop
        for (Book bk : bks) {
  
            // Printing the title and author name of book on
            // console
            System.out.println("Title : " + bk.title
                            + " and "
                            + " Author : " + bk.author);
        }
    }
}


Output:

Title : EffectiveJ Java and  Author : Joshua Bloch
Title : Thinking in Java and  Author : Bruce Eckel
Title : Java: The Complete Reference and  Author : Herbert Schildt

Output Explanation: In the above example, a library can have a number of books on the same or different subjects. So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. books can not exist without libraries. That’s why it is composition. Book is Part-of Library.

Difference Between Aggregation and Composition in Java

Aggregation 

Composition 

Aggregation can be described as a “Has-a” relationship, which denotes the association between objects. Composition means one object is contained in another object. It is a special type of aggregation (i.e. Has-a relationship), which implies one object is the owner of another object, which can be called an ownership association.
There is mutual dependency among objects. There is a unidirectional relationship, this is also called “part of” relationship.
It is a weak type of association, both objects have their own independent lifecycle. It is a strong type of association (aggregation), the child object does not have its own life cycle. 
The associated object can exist independently and have its own lifecycle.  The child’s life depends upon the parent’s life. Only the parent object has an independent lifecycle.
UML representation of White Diamond denotes aggregation. UML representation of Black Diamond denotes composition.
For example, the relationship between a student and a department. The student may exist without a department. For example, a file containing in a folder, if the folder deletes all files inside will be deleted. The file can not exist without a folder.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!