×

Aggregation in Java

Aggregation

A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation. Another class is referred to as belonging to the aggregate class since it has a reference to it. Each class that is referred to is regarded as being a component of the aggregate class.

Due to the fact that an aggregate connection cannot contain cyclic references, ownership happens. No unambiguous ownership can be shown, and the relationship is merely one of association if Class A and Class B both include references to one other. It symbolises the connection between Has-A.

It is a one-way, or unidirectional, association. For instance, a department may have students, but students can’t have departments, making this relationship unidirectional.

Since both items in Aggregation can persist on their own, eliminating one won't have an impact on the other.

Let’s learn this topic in an easier way with an example code.

//Java application to display the
// The Concept of the Aggregation
// importing the necessary classes
import java.io.*;
import java.util.*;
// Class 10
// learner class
class Learner {
// Qualities of a Learner
String name;
int id;
String cate;
// Constructor of the learner class
Learner(String name, int id, String cate)
{
// The present instance is referred to by this keyword.
this.name = name;
this.id = id;
this.cate = cate;
}
}
// Class 9
// Objects for learners are included in the category class.
// It connects to the learner class due to its Objects.
class Category {
// Qualities of the Category class
String name;
private List Learners;
Category(String name, List Learners)
{
// this term designates the actual instance being used.
this.name = name;
this.Learners = Learners;
}
// The category class method
public List getLearners()
{
// giving back a list of user-defined types
// type of learner
return Learners;
}
}
// Class 8
// List of Categories in a University Class
// Objects. It is associated with the Category
// class employing its Objects
class university {
// Qualities of the university
String universityName;
private List Categories;
// Constructor of the university class
university(String universityName,List Categories)
{
// The present instance is referred to by this keyword.
this.universityName = universityName;
this.Categories = Categories;
}
// Method of the university class
// Number of Learners in Total across All Categories
// in a given university
public int getTotalLearnersInuniversity()
{
int noOfLearners = 0;
List Learners;
for (Category cate : Categorys) {
Learners = .getcateLearners();
for (Learner s : Learners) {
noOfLearners++;
}
}
return noOfLearners;
}
}
// Class 7
// main class
class Kamal {
// main driver method
public static void main(String[] args)
{
// Creating object of learner class inside main()
Learner h1 = new Learner("Konda", 10, "EEE");
Learner h2 = new Learner("Sahithi", 12, "EEE");
Learner h3 = new Learner("Uppi", 13, "IT");
Learner h4 = new Learner("Hymavathi", 21, "IT");
// Making a List of Learners in EEE
List cse_Learners = new ArrayList();
// Adding the EEE Learners
cse_Learners.add(h1);
cse_Learners.add(h2);
// making a List of IT Learners
List it_Learners
= new ArrayList();
// Adding EE Learners
it_Learners.add(h3);
it_Learners.add(h4);
// making objects of IT and EEE class the inside
// main()
Category EEE = new Category("EEE", eee_Learners);
Category IT = new Category("IT", it_Learners);
List Categories = new ArrayList();
Categories.add(EEE);
Categories.add(IT);
// Lastly, creating an instance of the university
university university = new university("BVRIT", Categories);
// Display the message for easier reading
System.out.print("Total Learners in the university: ");
// getting the total number of students by calling a method
// in the university and printing on console
System.out.print(university.getTotalLearnersInuniversity());
}
}

Output:

Aggregation in Java

Explanation of the output:

In this illustration, there is a university with numerous categories, including EEE and IT. There are  in every category. So, we create a category class object or number of objects (i.e., List of Objects) by referencing it in the university class. It indicates that the category class's Object links the university class to the category class (s). Additionally, the category class refers to the learner class's Objects or Objects (i.e., List of Objects), indicating that it is connected to the learner class via its Object (s). It stands for a Has-A relation. In the aforementioned illustration: the learner Student possesses a name. The learner has an ID. A category. Has A Learner category   Has learners.

When should you utilise aggregation?

  1. In situations with no is-a relationship, aggregation also yields the best results for code reuse.
  2. If the relationship is maintained throughout the lifespan of the objects involved, inheritance should only be utilised; otherwise, aggregation is the preferable option.

Related Topics

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.