In the real world, nothing exists in a vacuum. A doctor has patients, a driver has a car, and a student enrolls in courses. These are all relationships—connections that define how different entities interact.
When we build software using Object-Oriented Programming (OOP), our goal is to model this real world.
So, how do we represent these connections between our objects?
In this chapter, we will explore the most fundamental and common of these relationships: Association.
Association represents a relationship between two classes where one object uses, communicates with, or references another.
This relationship answers the question:
“Does one object need to know about the existence of another object to perform its responsibilities?”
If the answer is yes, there is an association between them.
Think of a Student and a Teacher.
However:
This is a real-world association:
Association comes in multiple forms depending on:
These forms are often combined. For example, a bidirectional one-to-many relationship exists between an Author
and multiple Book
s.
In a unidirectional association, only one class is aware of the other.
Example: A Car
has a Driver
, but the Driver
doesn't know about the Car
.
Car
knows about the Driver
and interacts with it.Driver
class is completely unaware of the Car
.In a bidirectional association, both classes are aware of each other and can reference one another.
Example: An Author
writes multiple Book
s, and each Book
knows its Author
.
In this bidirectional association:
Author
has a list of Book
s.Book
stores a reference to its Author
.This is a two-way communication channel between the classes.
In UML class diagrams, association is represented by a solid line between two classes:
Multiplicity can also be marked:
1
for one*
for manyUse association when: