Association, Composition, and Aggregation in Java

by | Jan 6, 2023 | Java

Association in Java

Association, as the name suggests, is the relation between two classes. The relation is established between the objects of the two classes. Like the mathematical model of sets, association can be one to one, one to many, many to one, or many to many. Association is the process by which two objects of two different classes communicate such that the functionalities and services offered by both the objects can be evenly shared. The two types of association in Java are Composition and Aggregation. The program below demonstrates the concept of association between two objects:

Sample Code

import java.io.*;
class Bank
{
private String name;
// name of the bank
Bank (String name)
{
this.name = name;
}
public String getBankName ()
{
return this.name;
}
}
class Employee
{
private String name;
Employee (String name)
{
this.name = name;
}
public String getEmployeeName ()
{
return this.name;
}
}
//Method that shows how association is carried out in the classes
class Association
{
public static void main (String args [])
{
Bank bank = new Bank (“ Axis ”);
Employee emp = new Employee (“ Neha “);
System.out.println (emp. getEmployeeName () + “ is an employee of the ” + bank.getBankName () );
}
}

 

OUTPUT

Neha is an employee of the Axis

In the sample code above, we see that two classes have been created, namely Bank and Employee. Both these classes are associated with their objects. Employees work in a bank, and a bank can have several employees. Therefore, the relationship between the bank and the employee class is a one-to-many relationship.

Aggregation in Java

Aggregation, as mentioned above, is a special type of Association. The features of this kind of association are:

  • Aggregation represents the ‘Has – A’ kind of relationship.
  • Aggregation is a one-way relationship. Therefore, it is also called a unidirectional relationship. As a simple example, a school can have students inside it, but the reverse is not possible. That is, a school cannot be inside a school. These kinds of relationships are called unidirectional relationships.
  • In aggregation, both of the entries can exist individually. That is, if one of the entries is removed, then the other entry can survive independently.

The following is a Java program to illustrate the concept of Aggregation better:

//This program demonstrates aggregation
import java.util.*;
import java.io.*;
Class Student
{
String name;
int id;
String dept;
Student (String name, int id, String dept)
{
this.name = name;
this.id = id;
this.dept = dept;
}
}
//There are many student objects under the department class. The mode of association between //department and student is the objects of the student class.
class Department
{
String name;
private List <Student> students ;
Department (String name, List <Student> students )
{
this.name = name;
this.students = students;
}
public List <Student> getStudents ()
{
return students;
}
}
//There are many department objects under the institute class. The mode of association between department and institute is the objects of the department class.
class Institute
{
String instituteName;
private List <Department> departments;
Institute (String instituteName, List <Department> departments)
{
this.instituteName = instituteName;
this.departments = departments;
}
//returns total students
public int getTotalStudentsInInstitute ()
{
int noOfStudents = 0;
List <Student> students;
for (Department dept : departments)
{
students = dept.getStudents ();
for (Student s : students )
{
noOfStudents++;
}
}
return noOfStudents;
}
}
//Driver function
class Demo
{
public static void main (String args [])
{
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”);
//all CSE department students
List <Student> cse_students = new ArrayList <Student> ();
cse_students.add (s1);
cse_students.add (s2);
//all EE department students
List <Student > ee_students = new ArrayList <Student >();
ee_students.add (s3);
ee_students.add (s4);
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);
//Object creation
Institute institute = new Institute (“King’s College London”, departments);
System.out.println (“Total number of Students in the institute are : ”);
System.out.println ( Institute.getTotalStudentsInInstitute () ) ;
}
}

 

OUTPUT

Total students in institute: 4

Explanation of Code:

The code here refers to an Institution named King’s College London, which has two departments, namely the CSE department and the EE department. Every department has a fixed number of students. Therefore, an institute class has been created with reference to the Object or the List of objects (number of objects) of the Department class. Therefore, this clearly states a relationship between the department class objects with the Institute class. The department class also contains references to objects or a list of objects similar to the Institute class of the Student class. Thus, there is again an established relationship between the Department class and the objects of the student class. It represents a Has-A relationship.

Why is Aggregation Used?

Aggregation is one technique through which code reusability is best achieved.

Composition in Java

Composition is a more tightly coupled version of Aggregation. Here the two entities are extremely dependent on each other. Some of the features of Composition are as follows:

  • The composition represents a part-of relationship
  • As mentioned before, the dependency between the two entities is extremely high in the case of composition.
  • The composed object cannot exist without the other object if there is a composition between two entities. Thus, the two objects are not independent.

The following code illustrates the concept of Composition better with the help of a Java Program.

Sample Code

// Composition example
import java.io.*;
import java.util.*;
class Book
{
public String title;
public String author;
Book (String title, String author)
{
this.title = title;
this.author = author;
}
}
class Library
{
// all books are referred to here
pruvate final List <Book> books;
Library (List <Book> books)
{
this.books = books;
}
public List <Book> getTotalBooksInLibrary ()
{
return books;
}
}
// Driver function
class Demo
{
public static void main (String args [])
{
// object creation of the book class
Book b1 = new Book (“The Psychology of Money”, “Morgan Housel”);
Book b2 = new Book (“My Grandpa once told me”, “Rudramani Pandey”);
Book b3 = new Book (“Rich Dad Poor Dad”, “Robert T. Kiyosaki”);
// All the books in the library are listed here in the array list
List <Book> books = new ArrayList <Book> ();
books.add (b1);
books.add (b2);
books.add (b3);
Library library = new Library (ooks);
List <Book> bks = library.getTotalBooksInLibrary ();
for (Book bk : bks)
{
System.out.println (“Title Name: ” + bk.title + “ and ” + “Author Name: ” + bk.author);
}
}
}

 

OUTPUT

Title Name: The Psychology of Money and Author Name: Joshua Bloch
Title Name: My Grandpa once told me and Author Name: Rudramani Pandey
Title Name: Rich Dad Poor Dad and Author Name: Robert T. Kiyosaki

Explanation

In the code above, a library class can contain one or more books on the same or different subjects. All the books in a library will get destroyed if, in an accident, the library gets destroyed or harmed. It follows the fact that books cannot exist independently without the library. The converse is also true. If there are no books in the library, the space can no longer be treated as a library.

Aggregation vs. Composition

  1. Dependency: Aggregation is a type of association where the two entities can independently exist, especially the child. In the case of a bank and an employee, even if you delete the bank, the record of the employee still remains. However, in composition, the child cannot exist without the support of the parent entity. For the example of the school, a school is only a school with its students inside. A student is only a student if he/she is affiliated with a particular school.
  2. Type of Relationship: Aggregation: ‘has – a’ and composition: ‘part-of’ relation.
  3. Type of Association: Composition is a stronger type of Association, whereas Aggregation is a weaker type of Association.

The following is an example to show the difference between Aggregation and Composition

Sample Code

import java.io.*;
// Since a car requires an engine to run, it will be used by the car. Therefore, there will an Engine //type field present in the car class.
class Engine
{
//starting an engine
public void work ()
{
System.out.println (“The engine of the car is started now”);
}
}
final class Car
{
//an engine is essential for a car to start rolling
private final Engine engine; // Composition example
// private Engine engine; // Aggregation example
Car (Engine engine)
{
this.engine = engine ;
}
// when you start the engine, you also start the car
public void move ()
{
//if (engine != null)
{
engine .work ();
System.out.println (“ Car is moving ” );
}
}
}
class Demo
{
public static void main (String args [])
{
// Object creation of the Engine class such that it can be used by the car
Engine engine = new Engine ();
Car car = new Car (engine);
car.move ();
}
}

 

OUTPUT

The engine of the car is started now
Car is moving

Explanation

In the case of aggregation, we have declared the Engine class to be non–final. This has been done keeping in mind that the engine is not always the do-all and end-all of the car. You can change the engine with some other internal part of the car. If need be, for purposes of repair, you can also remove the engine from a car. But even after doing that, your car still remains a car.

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.