Site icon DataFlair

Association In Java – Explore the Concepts of Composition & Aggregation

Java Association Tutorial

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Association in Java is a connection between two separate classes that is set up through their objects. Although Java association can balance one-to-one, one-to-many, and many-to-many relationships. It defines the multiplicity between objects.

There are two types of associations in Java

1. Aggregation

2. Composition

We will discuss in the tutorial with examples. So, let’s start the journey!

Association in Java

The association relationship indicates that a class knows about another class. It can be described as a “has-a” relationship between classes. The relationship between the classes can be bi-directional.

For example, if we talk about the association between a teacher and a student, multiple students can associate with a single teacher, and a single student is also associated with multiple teachers, but both can be created or deleted independently. So, when a teacher leaves the school, we don’t need to remove any students, and when a student leaves the school, we don’t need to remove any teachers.

So, in the above example, the teacher has many students and vice versa, connected to various objects. Thus, we can say the association in Java follows a many-to-many relationship.

Benefits of association in Java:

Java Association  Example –

package com.dataflair.association;
class Teacher
{
  private String name;
  Teacher(String name)
  {
    this.name = name;
  }
  public String getTeacherName()
  {
    return this.name;
  }
}
class Student
{
  private String name;
  Student(String name)
  {
    this.name = name;
  }
  public String getStudentName()
  {
    return this.name;
  }
}
class AssociationDemo
{
  public static void main (String[] args)
  {
    Teacher teacherObj = new Teacher("Rahul Sir");
    Student studentObj = new Student("Renuka");
    System.out.println(studentObj.getStudentName() +
        " is Student of " + teacherObj.getTeacherName());
  }
}

Output-

Types of Association in Java

There are two types of association in Java

 

Aggregation in Java

Now, Aggregation in Java is a special type of association. It has the following characteristics –

Let’s take the example of a mobile phone and a battery. A single battery can belong to a mobile phone, but if the mobile phone stops working, we delete it from our database. The phone battery will not be deleted because it may still be functional. So in aggregation, while there is ownership, objects have their own lifecycle.

package com.dataflair.association;

class Employees
{
  String name;
  int id ;
  String dept;
  Employees(String name, int id, String dept)
  {
    this.name = name;
    this.id = id;
    this.dept = dept;
    System.out.println("Employee name is "+name+" Id is "+id+" Department is "+dept);
  }
}
class Department
{
  String name, employees;
  Department(String name, String employees)
  {
    this.name = name;
    this.employees = employees;
  }

}
class Organization
{
  String officeName,departments;
  Organization(String officeName, String departments)
  {
    this.officeName = officeName;
    this.departments = departments;
  }

}

public class AggregationDemo{
  public static void main (String[] args)
  {
    Employees s1 = new Employees("Mia", 1, "Sales");
    Employees s2 = new Employees("Priya", 2, "Marketing");
    Employees s3 = new Employees("John", 1, "IT");
    Employees s4 = new Employees("Rahul", 2, "Designing");
  }
}

Output-

So, in this case, there is an organization that has a number of offices. Each office has a number of Departments. In this way, we influence an Organization to the class, which has a reference to an object or some Objects (i.e., Rundown of Objects) of the Department class. That implies the Organization class is related to the Department class through its Object(s). What’s more, the Department class has a reference to Object or Objects (i.e., Rundown of Objects) of the Employees class, likewise implying it is related to the Employees class through its Object(s). It speaks to a Has-A relationship. Code rescue can be best achieved by Aggregation in Java.

Composition in Java

This is a restricted form of Java aggregation where the quantities are highly dependent on each other. It represents a part-of relationship. One entity cannot exist without the other. Composition in Java represents a one-to-many relationship.

Suppose if we take an example of the relationship between questions and answers. Single questions can have multiple answers, but multiple answers can not have multiple questions. If we delete questions, answers will automatically be deleted. In this, the entities are dependent.

package com.dataflair.association;

import java.util.*;
class Book
{
  public String title;
  public String author;
  Book(String title, String author)
  {
    this.title = title;
    this.author = author;
  }
}
class Library
{
  private final List<Book> books;
  Library (List<Book> books)
  {
    this.books = books;
  }
  public List<Book> getTotalBooksInLibrary(){
    return books;
  }
}
public class CompositionDemo {

  public static void main (String[] args)
  {
    Book bookObj1 = new Book("Java:A Beginner's Guide","Herbert Schildt");
    Book bookObj2 = new Book("Core and Advanced Java", " Dreamtech Press");
    Book bookObj3 = new Book("Head First Java", "Kathy Sierra");
    List<Book> books = new ArrayList<Book>();
    books.add(bookObj1);
    books.add(bookObj2);
    books.add(bookObj3);
    Library library = new Library(books);
    List<Book> bks = library.getTotalBooksInLibrary();
    for(Book bk : bks){
      System.out.println("Title : " + bk.title + " and "
          +" Author : " + bk.author);
    }
  }
}

Output-

Choosing Between Aggregation and Composition in Java

While both aggregation and composition represent “has-a” relationships between objects, understanding the key differences is crucial for effective code design. Here’s a helpful guideline:

Summary

In conclusion, we can say

  1. Association follows many-to-many relationships.
  2. Aggregation follows a one-to-one relationship.
  3. The Composition follows a one-to-many relationship.

Now, you can apply any one of the above relationships with the help of examples. Hope you liked the explanation.

Drop your suggestion and feedback in the comment section.

Exit mobile version