(Translated by https://www.hiragana.jp/)
Association, Composition and Aggregation in Java - GeeksforGeeks
Open In App

Association, Composition and Aggregation in Java

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In object-oriented programming, relationships between classes play a crucial role in defining how objects interact with each other. Java, being an object-oriented language, provides mechanisms to model these relationships through association, aggregation, and composition. Aggregation, association, and composition in Java describe how instances of classes relate to each other.

An association can be considered a generic term to indicate the relationship between two independent classes; the relationship may be one-to-one, one-to-many, or many-to-many, but it need not indicate ownership.

Aggregation is a specific form of association in which one class, the whole, contains a collection of other classes, the parts; here, however, the lifecycle of the parts does not depend upon the whole. For example, a library and books show aggregation, since books may exist somewhere apart from the library.

In contrast, composition is a stronger form of aggregation that means ownership and lifecycle dependence; if the whole gets destroyed, then the parts no longer exist. For composition, a good example would be a house and its different rooms; a room cannot exist without a house.

Association, Aggregation, and Composition

Association

Association is the cardinal concept in object-oriented programming that describes the relationship between two independent classes. Association can be viewed as describing a “uses-a” relationship where an object uses, or in any way interacts with, another object. Association may be either unidirectional or bidirectional and may exist in several forms, such as one-to-one, one-to-many, many-to-one, and many-to-many.

Type of Association

Unidirectional Association:
This association is the one in which one class is aware and associated with another class; the reverse is not true. For example, the Student class can be associated with the LibraryCard class, for the association where the student has a library card; a LibraryCard does not need to ‘know about’ a Student.

Bidirectional Association:
In this type of association, the classes are aware of each other and interact with one another. For example, a Teacher class and a Classroom class may be associated bidirectionally; there would be a teacher assigned to a classroom, and a classroom would know to which teacher it is assigned.

Association Example:

Java
// Java Program to illustrate the
// Concept of Association

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Bank class
class Bank {

    // Attributes of bank
    private String bankName;
    private Set<Employee> employees;
  
    // Constructor of Bank class
    public Bank(String bankName)
    {
        this.bankName = bankName;
    }

    // Method of Bank class
    public String getBankName()
    {
        // Returning name of bank
        return this.bankName;
    }

    public void setEmployees(Set<Employee> employees)
    {
        this.employees = employees;
    }
  
    public Set<Employee> getEmployees()
    {
        return this.employees;
    }
}

// Class 2
// Employee class
class Employee {
  
    // Attributes of employee
    private String name;
  
    // Constructor of Employee class
    public Employee(String name)
    {
        // this keyword refers to current instance
        this.name = name;
    }

    // Method of Employee class
    public String getEmployeeName()
    {
        // returning the name of employee
        return this.name;
    }
}

// Class 3
// Association between both the
// classes in main method
class AssociationExample {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating Employee objects
        Employee emp1 = new Employee("Ridhi");
          Employee emp2 = new Employee("Vijay");
        
          // adding the employees to a set
        Set<Employee> employees = new HashSet<>();
        employees.add(emp1);
          employees.add(emp2);

          // Creating a Bank object
          Bank bank = new Bank("ICICI");
      
          // setting the employees for the Bank object
        bank.setEmployees(employees);
        
          // traversing and displaying the bank employees 
          for (Employee emp : bank.getEmployees()) {
              System.out.println(emp.getEmployeeName()
                                 + " belongs to bank "
                                 + bank.getBankName());
        }
    }
}

Output
Ridhi belongs to bank ICICI
Vijay belongs to bank ICICI

Explanation of the above Program:

In the above example, two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, So, it is a one-to-many relationship. 

Association in Java

Aggregation

Aggregation is a relationship that comes under object-oriented programming, classifying an instance of a class as “has a.” It’s a form of association with weaker relationship strength, whereby the lifetime of the contained object (part) is not controlled based on the lifetime of the container object (whole). Concepts of aggregation are quite important for developing modular and reusable software components.

Aggregation is a type of association that represents a relationship where one class is a collection or container of another class. It depicts a “has-a” relationship, where the container object can exist independently of its contents, and the contained objects can exist independently of the container.

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 entries can survive individually which means ending one entity will not affect the other entity.
Aggregation in Java

Aggregation Example:

Java
// Java program to illustrate
// Concept of Aggregation

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Student class
class Student {

    // Attributes of Student
    private String studentName;
    private int studentId;

    // Constructor of Student class
    public Student(String studentName, int studentId)
    {
        this.studentName = studentName;
        this.studentId = studentId;
    }

    public int getstudentId() { 
      return studentId; 
    }

    public String getstudentName() {
      return studentName; 
    }
}

// Class 2
// Department class 
// Department class contains list of Students
class Department {

    // Attributes of Department class
    private String deptName;
    private List<Student> students;

    // Constructor of Department class
    public Department(String deptName, List<Student> students)
    {
        this.deptName = deptName;
        this.students = students;
    }

    public List<Student> getStudents() {
      return students; 
    }

    public void addStudent(Student student)
    {
        students.add(student);
    }
}

// Class 3
// Institute class
// Institute class contains the list of Departments
class Institute {

    // Attributes of Institute
    private String instituteName;
    private List<Department> departments;

    // Constructor of Institute class
    public Institute(String instituteName,
                     List<Department> departments)
    {
        // This keyword refers to current instance itself
        this.instituteName = instituteName;
        this.departments = departments;
    }

    public void addDepartment(Department department)
    {
        departments.add(department);
    }

    // Method of Institute class
    // Counting total students in the institute
    public int getTotalStudentsInInstitute()
    {
        int noOfStudents = 0;
        List<Student> students = null;

        for (Department dept : departments) {
            students = dept.getStudents();

            for (Student s : students) {
                noOfStudents++;
            }
        }
        return noOfStudents;
    }
}

// Class 4
// main class
class AggregationExample {

    // main driver method
    public static void main(String[] args)
    {
        // Creating independent Student objects
        Student s1 = new Student("Parul", 1);
        Student s2 = new Student("Sachin", 2);
        Student s3 = new Student("Priya", 1);
        Student s4 = new Student("Rahul", 2);

        // Creating an list of CSE Students
        List<Student> cse_students = new ArrayList<Student>();
        cse_students.add(s1);
        cse_students.add(s2);

        // Creating an initial list of EE Students
        List<Student> ee_students = new ArrayList<Student>();
        ee_students.add(s3);
        ee_students.add(s4);

        // Creating Department object with a Students list
        // using Aggregation (Department "has" students)
        Department CSE = new Department("CSE", cse_students);
        Department EE = new Department("EE", ee_students);

        // Creating an initial list of Departments
        List<Department> departments = new ArrayList<Department>();
        departments.add(CSE);
        departments.add(EE);

        // Creating an Institute object with Departments list
        // using Aggregation (Institute "has" Departments)
        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 the institute and printing on console
        System.out.print(
            institute.getTotalStudentsInInstitute());
    }
}

Output
Total students in institute: 4

Explanation of the above Program:

In this example,

  • There is an Institute which has no. of departments like CSE, 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 Institute class is associated with Department class through its Object(s).
  • And Department class has also a reference to Object 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. Department Has-A Students as depicted from the below media. 
 

Aggregation Example

Note: Code reuse is best achieved by aggregation.  

Composition 

Composition is a core concept in object-oriented programming that refers to the relationship “part-of” between classes. It is a stronger form of association in which the contained objects’ lifecycle is strongly associated with the container object’s lifecycle. The understanding of composition is crucial in the design of complex systems where objects of the system are composed of other objects.

Composition is a type of association meaning one class “contains” another. This association can be said to be a “part-of” relationship and would denote that the contained object is strongly connected with the containing object, the whole. The parts cannot be without the whole.

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.
Composition

Composition Example:

Java
// Java program to illustrate
// Concept of Composition

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Department class
class Department {

    // Attributes of Department
    public String departmentName;

    // Constructor of Department class
    public Department(String departmentName)
    {
        this.departmentName = departmentName;
    }

    public String getDepartmentName()
    {
        return departmentName;
    }
}

// Class 2
// Company class
class Company {

    // Reference to refer to list of books
    private String companyName;
    private List<Department> departments;

    // Constructor of Company class
    public Company(String companyName)
    {
        this.companyName = companyName;
        this.departments = new ArrayList<Department>();
    }

    // Method
    // to add new Department to the Company
    public void addDepartment(Department department)
    {
        departments.add(department);
    }

    public List<Department> getDepartments()
    {
        return new ArrayList<>(departments);
    }

    // Method
    // to get total number of Departments in the Company
    public int getTotalDepartments()
    {
        return departments.size();
    }
}

// Class 3
// Main class
class CompositonExample {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating a Company object
        Company techCompany = new Company("Tech Corp");

        techCompany.addDepartment(new Department("Engineering"));
        techCompany.addDepartment(new Department("Operations"));
        techCompany.addDepartment(new Department("Human Resources"));
        techCompany.addDepartment(new Department("Finance"));

        int d = techCompany.getTotalDepartments();
        System.out.println("Total Departments: " + d);

        System.out.println("Department names: ");
        for (Department dept : techCompany.getDepartments()) {
            System.out.println("- " + dept.getDepartmentName());
        }
    }
}

Output
Total Departments: 4
Department names: 
- Engineering
- Operations
- Human Resources
- Finance

Explanation of the above Program:

In the above example,

  • A company can have no. of departments.
  • All the departments are part-of the Company.
  • So, if the Company gets destroyed then all the Departments within that particular Company will be destroyed, i.e. Departments can not exist independently without the Company.
  • That’s why it is composition. Department is Part-of Company.

Difference Between Association, Aggregation and Composition

Feature

Association

Aggregation

Composition

Definition

General relationship between two classes

A special form of association with a “has-a” relationship

A stronger form of association with a “part-of” relationship

Dependency

Classes are related but can exist independently

Contained objects can exist independently of the container object

Contained objects cannot exist without the container object

Lifecycle

Independent lifecycles

Independent lifecycles

Dependent lifecycles

Ownership

No ownership implied

Shared ownership

Exclusive ownership

Strength

Weak

Moderate

Strong

Cardinality

One-to-one, one-to-many, many-to-one, many-to-many

One-to-one, one-to-many, many-to-one, many-to-many

One-to-one, one-to-many

Example

Teacher and Student

Library and Books

Car and Engine

Representation

Uses a direct reference

Uses a reference to the contained object(s)

Contains instances of the contained object(s)

Illustrative Example Code

java class
Teacher { private
Student student;
}

java class
Library { private
List<Book> books;
}

java class
Car { private
Engine engine;
}



Previous Article
Next Article

Similar Reads

Difference Between Aggregation and Composition in Java
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.  AggregationIt is a special form
6 min read
Hibernate - Bidirectional Association
Hibernate is a powerful open-source framework for Java that provides an object-relational mapping solution. It simplifies the process of working with databases which allow developers to map Java objects with the data present in the database tables. Hibernate handles the data persistence which allows developers to focus more on object-oriented aspec
6 min read
Difference between Inheritance and Composition in Java
Inheritance: When we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. In doing this, we can reuse the fields and methods of the existing class without having to write them ourself. A subclass inherits all the members (fields, methods, and nested
3 min read
Composition in Java
The composition is a design technique in java to implement a has-a relationship. Java Inheritance is used for code reuse purposes and the same we can do by using composition. The composition is achieved by using an instance variable that refers to other objects. If an object contains the other object and the contained object cannot exist without th
4 min read
Favoring Composition Over Inheritance In Java With Examples
In object-oriented programming (OOP), choosing between inheritance and composition is crucial for designing flexible and maintainable code. This article explores why you should favor composition over inheritance, with simple explanations and examples. What is Inheritance?Inheritance is when a new class is based on an existing class. The new class (
3 min read
Messages, aggregation and abstract classes in OOPS
Object-Oriented Programming System (OOPS) is the basic concept of many programming languages. It is a paradigm based on the object which contains methods and data. This concept is used to make programming a class and object model which behaves like a real-world scenario. In this article, we'll learn about messages, aggregation, composition and abst
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Difference between a Java Application and a Java Applet
Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications, it can be run with or without it. Java Applet is a Java program that can be embedded into a web pa
3 min read
Difference between Java IO and Java NIO
Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO API's. In this article, the difference between these two IO pack
3 min read
Difference between Java and Core Java
Java is a very famous language that is based on the object-oriented programming concepts. It is the successor of the C and C++ languages. It was developed by Sun Microsystems. Core Java is a term used by Sun Microsystems to refer to the Java to standard edition J2SE. This is the parent of all other editions of Java used on internet sites. It has a
2 min read
Why java.lang.VerifyError Occurs in Java and How to Solve this?
The Java Virtual Machine (JVM) distrusts all loaded bytecode as a core tenet of the Java Security Model. During runtime, the JVM will load .class files and attempt to link them together to form an executable — but the validity of these loaded .class files is unknown. To ensure that the loaded .class files do not pose a threat to the final executabl
6 min read
Difference Between java.lang and java.util
Java Packages contain classes, interfaces, and sub-packages. The packages java.lang and java.util are two of the most commonly used packages in Java Standard Library. Both packages contain useful classes and utilities. In this article, we will learn about java.lang and java.util package with examples and also the difference between these two packag
2 min read
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
There are two variants of descending() in Java.util.TreeMap, both are discussed in this article. 1. descendingKeySet(): It returns a reverse order Navigable Set view of the keys contained in the map. Syntax : public NavigableSet descendingKeySet() Parameters: NA Return Value: It returns a reverse order navigable set view of the keys in this map. Ex
3 min read
Java.util.TreeMap.containskey() and containsValue() in Java
There are two variants of contains() in Java.util.TreeMap, both are discussed in this article. 1. containskey(Object o) : It returns true if the map contains a mapping for the specified key. Parameters: o : The key which will be tested whether present or not. Return Value: Returns true if there is a mapping for the given key. Exception: ClassCastEx
2 min read
Java.util.TreeMap.put() and putAll() in Java
The insertion in TreeMap are handled using the variants of the put functions. There are two variants of put() in Java.util.TreeMap, both are discussed in this article. 1. put() : It associates the specified value with the specified key in the map. If a key is already present, then updating it results in updation of that key. Parameters: key : The k
4 min read
Difference between Core Java and Advanced Java
Java is a versatile and widely used programming language that helps in the development of many software applications. It is popular for its portability, robustness, and ease of use, making it a preferred choice for both beginners and experienced developers. Java's ecosystem can be largely categorized into two main parts that are Core Java and Advan
4 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Article Tags :
Practice Tags :