Association In Java – Explore the Concepts of Composition & Aggregation

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 Association

  1. Aggregation
  2. Composition

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

Association in Java

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

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-

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Association-example in Java

Types of Association in Java

There are two types of association in Java

Types of Association in Java

 

Aggregation in Java

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

  • It represents the Has-A relationship.
  • Aggregation in Java follows a one-way or one-to-one relationship.
  • Ending one entity won’t affect another, both can be present independently.

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, and 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.

Java Aggregation with example

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-
Aggregation-example in Java

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 Object or number of Objects (i.e. Rundown of Objects) of the Department class. That implies Organization class is related to Department class through its Object(s). What’s more, Department class has likewise a reference to Object or Objects (i.e. Rundown of Objects) of Employees class implies it is related to Employees class through its Object(s). It speaks to a Has-A relationship. Code rescue can be best achieved by Aggregation in Java.Organization Example

Composition in Java

This is a restricted form of Java aggregation that is 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.

Java Composition with example

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-

Composition-program in Java

Choosing Between Aggregation and Composition

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:

  • Use aggregation when the objects can exist independently. In the example of a mobile phone and battery, the phone can function without a battery (albeit temporarily), and the battery could potentially be used in another device. In such scenarios, aggregation is suitable as objects have their own life cycles.
  • Use composition when the parts have a strong dependency on the whole. Consider a car engine. The engine’s parts ( pistons, valves, crankshaft) are intrinsically linked to the engine’s functionality and wouldn’t exist independently. When destroying the car, the engine and its parts are typically disposed of together. In these cases, composition is more appropriate as the parts rely on the whole object for their existence.

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.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

3 Responses

  1. Shravya Kodli says:

    how that public lis works?
    and i have a question of how to remove object from dependent class and see the effect on other class?

  2. Naga Ganjala says:

    I think you have to revise your summary.

    1.Association follows all 4 associations
    2.There is no rule like composition should follow only one-to-many relationship.
    It can be one-to-one or any of four also ex: Human and heart -strong relation ship one cannot
    exist without other.
    3.Similarly Aggregation –it can have any 4 associations but it should be week association.

  3. Zakariye Mohamud says:

    incredible note for UML Relationship and types.

    Thanks to Data Fliar community..

Leave a Reply

Your email address will not be published. Required fields are marked *