Aggregation in Java is a specialized form of association that represents a "has-a" relationship between two classes, indicating that one class contains instances of another class. It's a key concept in object-oriented programming and describes how objects can be related without implying strong ownership.
Understanding Aggregation
-
"Has-a" Relationship: This signifies that one class has an instance of another class as a member variable. For example, a
Department
has multipleProfessor
objects. -
Weak Relationship (Looser Coupling): Unlike composition, aggregation implies a weaker relationship. The contained object can exist independently of the container object. If the container object is destroyed, the contained object may continue to exist.
-
Unidirectional: Aggregation is usually unidirectional, meaning that one class knows about the other, but not vice-versa. The
Department
knows about theProfessor
objects within it, but typically theProfessor
doesn't have a direct reference back to theDepartment
.
Aggregation vs. Composition
Feature | Aggregation | Composition |
---|---|---|
Relationship | "Has-a" | "Part-of" |
Dependency | Weak; contained object can exist independently | Strong; contained object cannot exist independently |
Lifecycle | Contained object's lifecycle is independent | Contained object's lifecycle is tied to the container object |
Example | Department and Professor |
Car and Engine |
Example in Java
// Professor class
class Professor {
private String name;
public Professor(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
// Department class
class Department {
private String name;
private Professor head;
public Department(String name, Professor head) {
this.name = name;
this.head = head;
}
public String getName() {
return name;
}
public Professor getHead() {
return head;
}
}
public class Main {
public static void main(String[] args) {
Professor professor1 = new Professor("Dr. Smith");
Department scienceDepartment = new Department("Science", professor1);
System.out.println(scienceDepartment.getName() + " Department Head: " + scienceDepartment.getHead().getName());
}
}
In this example, a Department
has a Professor
object representing the department head. If the Department
object is destroyed, the Professor
object still exists. This showcases the independent lifecycle aspect of aggregation.
Key Benefits of Aggregation
- Code Reusability: Promotes reusability by allowing classes to utilize other classes as parts of their structure.
- Flexibility: Offers greater flexibility in designing relationships between classes.
- Reduced Coupling: Reduces dependencies between classes, making the system more maintainable and easier to change.
In conclusion, aggregation is a valuable tool in object-oriented design that allows you to model "has-a" relationships between classes in a flexible and maintainable way. It enhances code reusability and reduces coupling by enabling objects to exist independently of each other.