Aggregation in Java


In java programming language if the class has an entity reference then it will known as Aggregation. In java the aggregation represents HAS-A relationship.

Suppose we have a class Student and this class contains information about the student for example it has the id, name, class, email address or the student. This class has another object called address which further has much information such as city, country, postal code, etc. In this type of case the Student will have an entity reference that is address, therefore, relationship Student HAS-A address.


Why aggregation is used?

In Java programming language aggregation is used to re use the code.


Simple example of aggregation:

Consider the following example in which we have created two classes and used the reference of one class in the other class:

CODE:

class Function {

int square (int x) {

return x * x ;

}

}

class Circle {

Function func;

double pi = 3. 14;

double area (int r) {

func = new Function ();

int sq = func. square (radius);

return pi * sq;

}

public static void main (string args []) {

Circle c1 = new Circle ();

double result = c1. area (5);

system. out. println (result);

}

}

OUTPUT:

78.5


When use aggregation?

In java programming language, when there is no is- a relationship then aggregation will be the best option to make the code reusable. If the programmer wants to use inheritance in the program then the relationship “is- a” should be maintained throughout the program and throughout the lifetime of the objects in the program. If the relationship “is- a” cannot be maintained then aggregation will be the best option.


Understanding meaningful example of Aggregation:

Consider the following example in which in which we have a student and the student has an object address. The address further has information such as city, country, postal code, state, etc. In this example the relationship is Student HAS- A address.

Address.java:

CODE:

Public class Address {

String city, state, country;

Public Address (string city, string state, string country) {

this. city = city;

this. state = state;

this. country = country;

}

}

Stu.java:

CODE:

Public class Stu {

int roll;

string name;

Address address;

Public Stu (int roll, string name, Address address) {

this. roll = roll;

this. name = name;

this. address = address;

}

Void display () {

System.out. println (roll + “ ” + name);

System.out. println (address. City + “” + address. State + “” + address. Country);

}

Public static void main (string [] args) {

Address add1 = new Address (“Toronto”, “Ontario”, “Canada”);

Address add2 = new Address (“Quebec”, “Ontario”, “Canada”);

Stu s1 = new Stu (121, “Stuart”, add1);

Stu s2 = new Stu (122, “Bill”, add2);

s1. display ();

s2. display ();

}

}

OUTPUT:

121 Stuart

Toronto Ontario Canada

122 Bill

Quebec Ontario Canada