Register Login

Association, Aggregation and Composition in Java

Updated Sep 26, 2019

This article is focused on three of the most important OOP concepts in Java, namely association, composition, and aggregation. Although they are related concepts, there are some differences in the way they are used to connect two classes. Association is the relation between two classes that are based on their objects. Both Aggregation and Composition are two types of association.

Association in Java

Association in Java is the relationship established between two classes made possible through their objects. This relationship can be one to one, one to many, many to one and many to many.

For Example, an Organization and Employee are two different entities but the relationship between the Organization and Employee is one to many because an Organization could many employees. This the relationship between the two entities is called association.

Example of Association in Java

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    Organ organization = new Organ();
    organization.setOrganizationName("Michel Page");   
    Empl empl1 = new Empl();
    empl1.setEmployeeName("Manoj");
    Empl empl2 = new Empl();
    empl2.setEmployeeName("Raghav");   
    List<Empl> empList = new ArrayList();
    empList.add(empl1);
    empList.add(empl2);   
    organization.setEmployees(empList);   
    System.out.println(organization.getEmployees()+" are Employees of "+
        organization.getOrganizationName());
  }
}
class Organ {
  private String organizationName; 
  List<Empl> empl1;
  public String getOrganizationName() {
    return organizationName;
  }
  public void setOrganizationName(String organizationName) {
    this.organizationName = organizationName;
  }
  public List<Empl> getEmployees() {
    return empl1;
  }
  public void setEmployees(List<Empl> empl1) {
    this.empl1 = empl1;
  }
}
class Empl {
  private String employeeName;

  public String getEmployeeName() {
    return employeeName;
  }
  public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
  }
  @Override
  public String toString() {
    return employeeName;
  }
}

Output

[Manoj, Raghav] are Employees of Michel Page

Why use Association in Java?

Association is used to establish a relation between objects of two separate classes that can be two entirely different entities. This relationship indicates that a particular class is aware of another class and holds a reference to that class.

When to use Association in Java?

Association is applied when two classes need to interact with each other through their objects to achieve a certain result. It establishes a way to connect one or more objects with the objects of other classes.

These multidirectional connections are performed successfully through two of Association’s forms:

  • Composition
  • Aggregation.

Aggregation in Java

It is a special form of Association that is used to develop a one-way relationship between two classes. It is also called a unidirectional association and is used to represent a HAS-A relationship.

Example of Aggregation in Java

// Example code of Aggregation:
public class Main {
  public static void main(String[] args) {
    Add add = new Add();
    add.sethouseno("110");
    add.setsociety("Gokuldham");
    add.setCity("Chandighar");
    Emp emp = new Emp();
    emp.setId(475);
    emp.takeName("Rhagvendra");
    emp.setAdd(add);
    System.out.println("Employee Details :: " + emp);
  }
}
class Emp {
  private int id;
  private String name;
  // define employee's address
  private Add add; 
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String takeName() {
    return name;
  }
  public void takeName(String name) {
    this.name = name;
  }
  public Add getAdd() {
    return add;
  }
  public void setAdd(Add add) {
    this.add = add;
  }
  @Override
  public String toString() {
    return "Employee{" + "id=" + id + ", Name=" + name + ", Address=" + add + '}';
  }
}
class Add {
  private String houseno;
  private String society;
  private String city;
  public String gethouseno() {
    return houseno;
  }
  public void sethouseno(String houseno) {
    this.houseno = houseno;
  }
  public String getsociety() {
    return society;
  }
  public void setsociety(String society) {
    this.society = society;
  }
  public String getCity() {
    return city;
  }
  public void setCity(String city) {
    this.city = city;
  }
  @Override
  public String toString() {
    return "Address{" + "doorNo=" + houseno + ", society=" + society + ", city=" + city + '}';
  }
}

Output 

Employee Details :: Employee{id=475, Name=Rhagvendra, Address=Address{doorNo=110, society=Gokuldham, city=Chandighar}}

Example 2) Aggregation is also can be used for code re-usability.

// show simple aggregation example HAS A relation between car and engine.
class engine{
   public void show(){
      System.out.println("The Engine is a main part of the car .");
   }
}
public class Main {
   public static void main(String args[]){
      //Engine class object in Car class
      engine obj = new engine();
      obj.show();
   }
}

Output 

The Engine is a main part of the car.

Why use Aggregation in Java?

We use aggregation when want to reuse the code in our program. For example, Object A1 has a reference to another object called Object A2. They have a HAS-A relationship between them. As the Object A1 has reference to Object A2, the functionalities of Object A2 can be used by Object A1. Similarly, any class having a reference to Object A2 can utilize its methods.

When to use Aggregation in Java?

Aggregation is primarily used to connect two classes where the aggregate class has a reference to another class. This class has the ownership of the other class. When we want to avoid having cyclic references between the relationships of the two classes, we use this form of association.

Composition in Java

A Composition is a restricted form of aggregation where the two objects are highly dependent on each other. When a composition exists between two objects, the composed object cannot exist independently.

Example of Composition in Java

In this example, we will define a class Date to in order to maintain all information about the date and then we will define a class Employee which will not only contains members id, name and display () but will also contain a reference variable hireDate to refer joining information about the objects of class Date as its member, which maintains employee's hiring details.

As the execution is done,  emp.display () function will display employee's id, name and the hireDate. The hireDate is obtained as an implicit call to the Date class's toString () method.

// Example code of Composition
class date
{
  private int dy;
  private int mnth;
  private int yr;
  date(int dd, int mm,int yy)
  {
   System.out.println("Constructor is Called from date Class");
   dy=dd;
   mnth=mm;
   yr=yy;
  }
  public String toString()
  {
   return (dy+"/"+mnth+"/"+yr);
  }
}
 class Employee
{
  private int id;
  private String name;
  private date hiredate; //object of Data class
  Employee(int num,String n, date hire)
  {
   System.out.println(" Constructor is Called of Employee class");
   id=num ;
   name=n ;
   hiredate=hire;
  }
  public void display()
  {
   System.out.println("id = "+id);
   System.out.println("Name = "+name);
   System.out.println("Hiredate = "+hiredate);
  }
}
 public class Main
 {
   public static void main(String[] args)
    {
        date d = new date(31,03,2019);
        Employee emp = new Employee(10,"Rahul Tanwar",d);
        emp.display();
    }
 }

Output

Constructor is Called from date Class
Constructor is Called of Employee class
id = 10
Name = Rahul Tanwar
Hiredate = 31/3/2019

Example 2) 

package com.tutorial.javabasic;
 class Twowheelar {
  public String getDetails() {
  return "This is two wheelers details can be bike or scooter";
 }
}
 class bike extends Twowheelar {
}
 public class Main {
  public static void main(String[] s) {
 bike c = new bike();
 String details = c.getDetails();
 System.out.println(details);
 }
} 

Output:

This is two wheelers details can be bike or scooter 

Why Use Composition in Java?

Composition is used when we want to establish a PART-OF relationship between two objects and one must be dependent on the other.

When to use Composition in Java?

Composition in Java is used to make the code reusable but the code is preserved and encapsulation is not hampered. In addition, composition also allows better testing of classes, such as unit testing. In test-driven development, composition is often chosen over inheritance because of its usability.

Composition vs. Aggregation

Composition

Aggregation

Here, the two objects are highly dependent on each other. The child class cannot work without the parent class.

Here, two objects can exist independently. A child class can work freely without the parent class.

It is a form of strong association.

It is a form of weak association.

It has a PART-OF relationship between two objects.

It is a HAS-A relationship between two objects.

Summary

All the concepts discussed above are used in Java based on their type of relationship that has to be established between two classes. However, all the functionalities help in reusing the code written once and reducing the overall complexity.


×