Aggregation
Aggregation is a relationship between two classes in which one class has an instance of another class.
For example, when object A has a reference to another object B, we can say that object A has a HAS-A relationship with object B, and this is called Aggregation in Java Programming.
Aggregation helps in code reusability. Object B may contain useful methods that can be used by multiple objects. Any class that has object B can use its methods.
Create Project Name: StudentInformation
Source Code1: Address.java
public class Address {
String city, country;
public Address(String city, String country) {
this.city = city;
this.country = country;
}
}
Source Code2: Student.java
public class Student {
int id;
String name;
Address address; // Aggregation
public Student(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public void display() {
System.out.println("ID: " + id + ", Name: " + name);
System.out.println("City: " + address.city + ", Country: " + address.country);
}
}
Source Code3: StudentInformation.java
public class StudentInformation {
public static void main(String[] args) {
Address addr = new Address("Phnom Penh", "Cambodia");
Student s = new Student(101, "Seanghon", addr);
s.display();
}
}

