Association
About
Association is a fundamental relationship between two or more objects where they interact with each other but do not depend on each other for existence. It represents a "uses-a" or "knows-a" relationship in OOP.
Key Idea: Objects can interact with each other without being tightly coupled.
Association is not considered as one of the four fundamental OOP principles (Encapsulation, Abstraction, Inheritance, and Polymorphism). However, it is an important design concept within OOP.
Types of Association
One-to-One
One object is associated with only one other object.
A Person has one Passport.
One-to-Many
One object is associated with multiple objects.
A Teacher teaches many Students.
Many-to-One
Multiple objects are associated with one object.
Many Students study in one School.
Many-to-Many
Multiple objects are associated with multiple objects.
A Student enrolls in multiple Courses, and a Course has many Students.
Code Example: Association in Java
Example 1: One-to-One Association (A Person Has One Passport)
class Passport {
String passportNumber;
Passport(String passportNumber) {
this.passportNumber = passportNumber;
}
}
class Person {
String name;
Passport passport; // Association with Passport
Person(String name, Passport passport) {
this.name = name;
this.passport = passport;
}
void display() {
System.out.println(name + " has passport: " + passport.passportNumber);
}
}
public class Main {
public static void main(String[] args) {
Passport p1 = new Passport("A123456");
Person person1 = new Person("John", p1);
person1.display(); // Output: John has passport: A123456
}
}Correct Design: The Person and Passport exist independently but are associated.
Example 2: One-to-Many Association (A Teacher Teaches Many Students)
Correct Design: The Teacher knows the Students, but they exist independently.
Example 3: Many-to-Many Association (Students Enroll in Courses)
Correct Design: Students know Courses, and Courses know Students.
Example 4: Many-to-One Association (Multiple Students Study in One School)
Association vs. Aggregation vs. Composition
Feature
Association
Aggregation
Composition
Relationship
"Uses-a"
"Has-a" (Weak ownership)
"Has-a" (Strong ownership)
Lifespan Dependency
Independent
Independent
Dependent
Coupling
Loose
Loose
Strong
Example
A Teacher teaches a Student
A Library has Books, but books exist independently
A Car has an Engine, and the engine dies with the car
Association is more general than Aggregation and Composition.
Last updated