Java Aggregation - The Coding Shala

Home >> Learn Java >> Java Aggregation

Java Aggregation

Java Aggregation is a type of Association. It is a relationship between two classes like association. If a class has an entity reference, it is known as Aggregation. Aggregation is a directional association that means it is strictly a one-way association. Java Aggregation represents a HAS-A relationship.
Aggregation is a weak association. An association is said to be aggregation if both Objects can exist independently that means if one object is not there still another object can be used. For example a Bank and an Employee object. Bank has an employee. The Bank has multiple employees but an Employee can exist without a Bank also.
Another Example is a Class and a Student Object. Class and Student can exist independently.
Java Aggregation - The Coding Shala
Point to Remember: Code reuse is best achieved by aggregation.

Example of Aggregation in Java

The following example of Student and Address explains the Java Aggregation:
//Java Aggregation Example

class Address{
    String city;
    String State;
    
    Address(String city, String State){
        this.city = city;
        this.State = State;
    }
}

class Student{
    int id;
    String name;
    Address address;  //this is Aggregation, using Address entity reference
    
    Student(int id, String name, Address addr){
        this.id = id;
        this.name = name;
        this.address = addr;
    }
    
    void Display(){
        System.out.println("Student info below");
        System.out.println(this.id+" "+this.name);
        System.out.println("Address is: "+address.city+","+address.State);
    }
}

class Main{
    public static void main(String[] args){
        Address addr1 = new Address("Pune", "Maharashtra");
        Student s1 = new Student(1, "Akshay", addr1); //need to pass Address Object
        s1.Display();
        System.out.println();
        Address addr2 = new Address("Jaipur", "Rajasthan");
        Student s2 = new Student(2, "Rahul", addr2);
        s2.Display();
    }
}
Output:
Student info below
1 Akshay
Address is: Pune,Maharashtra

Student info below
2 Rahul
Address is: Jaipur,Rajasthan

In the above example, the Student has an address and Object address or Student object that can exist independently. Here we use Address object in Student class as a reference. 


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala