Aggregation in Java

๐Ÿง  What is Aggregation?

Aggregation is a type of association that represents a “has-a” relationship between two classes. It is a weaker relationship than inheritance and indicates that one class is a part of another class, but can exist independently.


๐Ÿ”ธ Real-World Example:

  • A Department has many Professors.

  • But a Professor can exist without a Department.


โœ… Syntax Example:

class Address {
String city, state;

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

class Employee {
int id;
String name;
Address address; // Aggregation

Employee(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}

void display() {
System.out.println(id + " " + name);
System.out.println(address.city + ", " + address.state);
}
}


๐Ÿงช Usage:

public class Main {
public static void main(String[] args) {
Address addr = new Address("Bangalore", "Karnataka");
Employee emp = new Employee(1, "Ravi", addr);
emp.display();
}
}

๐Ÿ“Œ Key Points:

  • Represents whole-part relationship.

  • Part can exist independently of the whole.

  • Promotes code reusability and flexibility.

 

Related Posts