Posted on: January 18, 2025Posted by: rahulgiteComments: 0
Association
Definition:
Association represents a relationship between two classes. It indicates how objects of one class are connected to objects of another class.
Types:
One-to-One: One instance of a class is associated with one instance of another class.
One-to-Many: One instance of a class is associated with multiple instances of another class.
Many-to-Many: Multiple instances of one class are associated with multiple instances of another class.
Key Points:
There is no ownership between the objects.
The lifespan of the objects is independent.
Example:
class Student {
private String name;
}
class Course {
private String title;
}
// A student can be associated with multiple courses, and courses can have multiple students.
Aggregation(Has-A Relationship)
Definition:
Aggregation is a specialized form of Association where one class represents a whole and the other represents a part. It defines a “has-a” relationship.
Key Points:
It is a weak form of association.
The part can exist independently of the whole.
Objects in an aggregation can have an independent lifecycle.
Example:
class Department {
private String name;
}
class Employee {
private String name;
}
// A department has employees, but employees can exist even without the department.
3. Composition (Strong Has-A Relationship)
Definition: A stronger form of aggregation where the contained object cannot exist independently of the container.
Example:
class Brain {
//...
}
class Human {
private final Brain brain = new Brain(); // composition
}
Note: If the container object is destroyed, the contained object is also destroyed.
Real-world analogy: A human has a brain. Without the human, the brain object doesn’t exist.
Key Differences
Aspect
Association
Aggregation
Definition
Describes a relationship between classes.
Represents a whole-part relationship.
Ownership
No ownership between objects.
Whole does not own the part.
Object Lifecycle
Objects have independent lifecycles.
Parts can exist independently of the whole.
Relationship
Ownership
Lifecycle Dependency
Example
Association
No
Independent
Student ↔ Teacher
Aggregation
Shared
Independent
School ↔ Department
Composition
Strong
Dependent
Human → Brain
Summary
Use Association to model general relationships between classes.
Use Aggregation when a “whole-part” relationship exists but the part does not depend on the whole.