Aggregation in Java

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.

  Has-a relationship is one in which an object of one class is created as a data member in another class.

Important points

  It represents Has-A relationship.

  Aggregation is a unidirectional association i.e. a one way relationship. For example, Department can have Students but vice versa is not possible and thus unidirectional in nature.

  In Aggregation, both the entries can survive individually which means ending one entity will not effect the other entity

Why use Aggregation?

Code reuse is best achieved by aggregation.

Example of Aggregation

Java program to illustrate the concept of Aggregation.

Create Student Class.

class Student 
    String name;
    int id ;
    String dept;
    Student(String name, int id, String dept) 
         = name; = id;
        this.dept = dept;

Create Department class.

class Department
	Student s; // Aggregation 
	Department(Student x)
	public void printDetail()
	System.out.println( +" : "" : "+s.dept);

Call these classes in main method

class Example 
	public static void main(String[] args)
		Student s=new Student("John",23,"IT");
		Department d=new Department(s);
John : 23 : IT

In above example Department has Student .This is HAS-A relationship.

woman avatar