Association — Objects That Know Each Other
Introduction
In a university system, a professor teaches courses and students enroll in them. A course knows who teaches it and who is in it, a professor knows the courses on their list, and a student knows the courses they take. None of these objects creates or owns the others. Each one is made on its own, and they keep references to each other so they can work together.
That relationship is called association: one object keeps a reference to another in a field, so it can reach it again later. This page shows how to draw it in a class diagram and how to keep it correct in code, where the hard part is changing both sides of a link together. The next three lessons build on it with the same university: Aggregation — Has-A with Independent Lifecycle, Composition — Has-A with Dependent Lifecycle and Dependency — Objects That Use Each Other.
What Is Association?
In UML, the language of class diagrams, an association says that objects of two classes can be linked. In code, a link is a field. Course has a field professor that holds a Professor object, and through it a course can ask its professor for a name. The link lasts as long as the field holds it: setting the field to another professor, or to nothing, ends it.
Think of the contacts on your phone. You have Alice's number and Alice has yours, so either of you can call the other. Deleting Alice's contact does not delete Alice, and losing your phone does not delete you. You are linked, and neither of you owns the other.
So when a class keeps another class's object in a field, you have an association. The object can call methods on the other through that field, and neither object makes or destroys the other; both can exist without the link. If an object is only handed over for one method call and never stored, that is a different relationship, dependency, which comes up again below.
UML also treats two stronger relationships as kinds of association. Aggregation and composition are associations with a diamond on one end, and the next two lessons are about them.
Direction and Multiplicity
An association can go one way. A Student may keep a reference to their Advisor while the Advisor class keeps no list of students: the student can reach the advisor, and the advisor cannot reach the student. Or it can go both ways. A Professor keeps the list of courses they teach and each Course keeps its professor, so either side can reach the other.
A two-way association is two references, one in each object, and the two have to agree. Most of the trouble with associations comes from that, and the code example below is built around it.
Multiplicity says how many objects can be at one end of a link. UML writes it as a range from the lowest number to the highest, with * for no upper limit:
| Notation | Meaning | Example |
|---|---|---|
1 | Exactly one | A student card belongs to exactly 1 student |
0..1 | Zero or one | A course has at most 1 professor, and none until one is assigned |
* | Zero or more, the same as 0..* | A professor teaches any number of courses, none included |
1..* | One or more | An order holds at least 1 item |
2..5 | From two to five | A project team has 2 to 5 members |
UML writes 1 for 1..1, and * for 0..*. The multiplicity also tells you what the field looks like in code. When the upper limit is 1, the field is a single reference, and it may be empty when the lower limit is 0: Course.professor starts empty, and the run below prints TBD for CS301, which never gets a professor. When the upper limit is above 1, the field is a list, like Course.students, Professor.courses and Student.courses.
UML Notation
Here is the university as a class diagram, with the objects of the run beside it. The boxes list each class's fields and methods under their Java names, so assign_course in Python is assignCourse there:

A solid line between two classes is an association. The UML specification puts it this way: "A binary Association is normally drawn as a solid line connecting two Classifiers", and a class is one kind of classifier.
Each end of the line carries a name and a multiplicity. The name is the field that holds the link, in the class at the other end: the end at Professor is called professor because Course keeps its professor in a field of that name. The number counts objects of the class it stands beside: 0..1 beside Professor says a course has at most one professor, and * beside Course says a professor can teach any number of courses.
An arrowhead shows which way a link can be followed. In the specification's words, "An open arrowhead on the end of an Association indicates the end is navigable.", which means the objects at the other end can reach the objects at that end. The line from Student to Advisor has one, because only the student keeps a reference. The two lines in the middle have none: the specification lets a diagram leave the arrowheads off the lines that both classes navigate and draw them only on one-way lines.
The words on a line, such as teaches, name the association, and the small filled triangle beside them shows which way to read it: Professor teaches Course, and Student enrolls in Course. The triangle is there "for documentation purposes only"; it says nothing about which class keeps the reference.
On the right are the objects after the first five calls of the run below. UML draws an object as an underlined name with its class, such as smith : Professor, and a line between two objects is one link. Smith is linked to two courses and Jones to none, which * allows. CS301 has no professor, which 0..1 allows.
See Both Sides Change
The interactive runs the listing's eight calls on its seven objects, one call at a time. Each link is two chips, one in each object's field, and the line between two cards is drawn only when both objects hold each other. Run it with Both sides first, the way the listing below works. Then start again with Own side first, where a call changes its own field first and never checks the other object's answer, and watch two links end up held from one side only.

Code Example
Here is the university in code. Each class keeps references to the others in its fields: a student's courses, a professor's courses, a course's professor and its students. The objects are made on their own, and the calls only link them. The methods keep both sides of each link in step: enroll asks the course first and adds the course to the student's list only when the course says yes, assign_course takes the course off its old professor's list before it goes on the new one, and drop ends the link on both sides. CS301 has a single seat, so the second student to ask for it is turned away:
from __future__ import annotations
class Student:
def __init__(self, name: str) -> None:
self._name = name
self._courses: list[Course] = [] # association: the courses this student is in
@property
def name(self) -> str:
return self._name
# Both sides change together: the course takes the student, or nothing changes
def enroll(self, course: Course) -> None:
if course in self._courses:
return
if not course.add_student(self):
print(f" {self._name} could not enroll: {course.title} is full")
return
self._courses.append(course)
print(f" {self._name} enrolled in {course.title}")
# Dropping ends the link on both sides; the course itself goes on
def drop(self, course: Course) -> None:
if course in self._courses:
self._courses.remove(course)
course.remove_student(self)
print(f" {self._name} dropped {course.title}")
def list_courses(self) -> None:
titles = ", ".join(c.title for c in self._courses)
print(f" {self._name}'s courses: {titles}")
class Professor:
def __init__(self, name: str) -> None:
self._name = name
self._courses: list[Course] = [] # association: the courses taught
@property
def name(self) -> str:
return self._name
# A course has one professor: a new one takes it off the old professor's list
def assign_course(self, course: Course) -> None:
if course in self._courses:
return
old = course.professor
if old is not None:
old._courses.remove(course)
self._courses.append(course)
course.set_professor(self)
print(f" Prof. {self._name} assigned to {course.title}")
def list_courses(self) -> None:
titles = ", ".join(c.title for c in self._courses)
print(f" Prof. {self._name} teaches: {titles}")
class Course:
def __init__(self, code: str, title: str, max_capacity: int = 30) -> None:
self._code = code
self._title = title
self._max_capacity = max_capacity
self._professor: Professor | None = None # association: its professor
self._students: list[Student] = [] # association: its students
@property
def title(self) -> str:
return self._title
@property
def professor(self) -> Professor | None:
return self._professor
def set_professor(self, professor: Professor) -> None:
self._professor = professor
def add_student(self, student: Student) -> bool:
if len(self._students) >= self._max_capacity:
return False
self._students.append(student)
return True
def remove_student(self, student: Student) -> None:
self._students.remove(student)
def get_info(self) -> None:
prof = f"Prof. {self._professor.name}" if self._professor else "TBD"
names = ", ".join(s.name for s in self._students)
print(f" {self._code}: {self._title} | Professor: {prof} | Students: {names}")
# Each object is made on its own; the associations only connect them
alice = Student("Alice")
bob = Student("Bob")
smith = Professor("Smith")
jones = Professor("Jones")
cs101 = Course("CS101", "Data Structures")
cs201 = Course("CS201", "Algorithms")
cs301 = Course("CS301", "Compilers Seminar", max_capacity=1)
print("Linking:")
smith.assign_course(cs101)
smith.assign_course(cs201)
alice.enroll(cs101)
alice.enroll(cs301)
bob.enroll(cs101)
bob.enroll(cs301)
print("Following the links:")
smith.list_courses()
bob.list_courses()
cs101.get_info()
cs301.get_info()
print("Changing the links:")
jones.assign_course(cs201)
alice.drop(cs101)
smith.list_courses()
jones.list_courses()
cs101.get_info()
alice.list_courses()import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Student {
private final String name;
// association: its courses
private final List<Course> courses = new ArrayList<>();
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
// Both sides change together: the course takes the student, or nothing changes
public void enroll(Course course) {
if (courses.contains(course)) {
return;
}
if (!course.addStudent(this)) {
System.out.println(" " + name + " could not enroll: "
+ course.getTitle() + " is full");
return;
}
courses.add(course);
System.out.println(" " + name + " enrolled in " + course.getTitle());
}
// Dropping ends the link on both sides; the course itself goes on
public void drop(Course course) {
if (courses.remove(course)) {
course.removeStudent(this);
System.out.println(" " + name + " dropped " + course.getTitle());
}
}
public void listCourses() {
System.out.println(" " + name + "'s courses: " + Course.titles(courses));
}
}
class Professor {
private final String name;
// association: the courses taught
private final List<Course> courses = new ArrayList<>();
public Professor(String name) {
this.name = name;
}
public String getName() {
return name;
}
// A course has one professor: a new one takes it off the old professor's list
public void assignCourse(Course course) {
if (courses.contains(course)) {
return;
}
Professor old = course.getProfessor();
if (old != null) {
old.courses.remove(course);
}
courses.add(course);
course.setProfessor(this);
System.out.println(" Prof. " + name + " assigned to " + course.getTitle());
}
public void listCourses() {
System.out.println(" Prof. " + name + " teaches: " + Course.titles(courses));
}
}
class Course {
private final String code;
private final String title;
private final int maxCapacity;
// association: its professor, and its students
private Professor professor;
private final List<Student> students = new ArrayList<>();
public Course(String code, String title, int maxCapacity) {
this.code = code;
this.title = title;
this.maxCapacity = maxCapacity;
}
public Course(String code, String title) {
this(code, title, 30);
}
public String getTitle() {
return title;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public boolean addStudent(Student student) {
if (students.size() >= maxCapacity) {
return false;
}
students.add(student);
return true;
}
public void removeStudent(Student student) {
students.remove(student);
}
public void getInfo() {
String prof = professor != null ? "Prof. " + professor.getName() : "TBD";
String names = students.stream().map(Student::getName)
.collect(Collectors.joining(", "));
System.out.println(" " + code + ": " + title + " | Professor: " + prof
+ " | Students: " + names);
}
public static String titles(List<Course> courses) {
return courses.stream().map(Course::getTitle).collect(Collectors.joining(", "));
}
}
public class UniversityDemo {
public static void main(String[] args) {
// Each object is made on its own; the associations only connect them
Student alice = new Student("Alice");
Student bob = new Student("Bob");
Professor smith = new Professor("Smith");
Professor jones = new Professor("Jones");
Course cs101 = new Course("CS101", "Data Structures");
Course cs201 = new Course("CS201", "Algorithms");
Course cs301 = new Course("CS301", "Compilers Seminar", 1);
System.out.println("Linking:");
smith.assignCourse(cs101);
smith.assignCourse(cs201);
alice.enroll(cs101);
alice.enroll(cs301);
bob.enroll(cs101);
bob.enroll(cs301);
System.out.println("Following the links:");
smith.listCourses();
bob.listCourses();
cs101.getInfo();
cs301.getInfo();
System.out.println("Changing the links:");
jones.assignCourse(cs201);
alice.drop(cs101);
smith.listCourses();
jones.listCourses();
cs101.getInfo();
alice.listCourses();
}
}#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
class Course;
// Each class keeps plain pointers to the others: it knows them and owns none of them
class Student {
public:
explicit Student(std::string name) : name_(std::move(name)) {}
const std::string& getName() const { return name_; }
// Both sides change together: the course takes the student, or nothing changes
void enroll(Course& course);
// Dropping ends the link on both sides; the course itself goes on
void drop(Course& course);
void listCourses() const;
private:
std::string name_;
std::vector<Course*> courses_; // association: its courses
};
class Professor {
public:
explicit Professor(std::string name) : name_(std::move(name)) {}
const std::string& getName() const { return name_; }
// A course has one professor: a new one takes it off the old professor's list
void assignCourse(Course& course);
void listCourses() const;
private:
std::string name_;
std::vector<Course*> courses_; // association: the courses taught
};
class Course {
public:
Course(std::string code, std::string title, int maxCapacity = 30)
: code_(std::move(code)), title_(std::move(title)), maxCapacity_(maxCapacity) {}
const std::string& getTitle() const { return title_; }
Professor* getProfessor() const { return professor_; }
void setProfessor(Professor* professor) { professor_ = professor; }
bool addStudent(Student& student) {
if (static_cast<int>(students_.size()) >= maxCapacity_) {
return false;
}
students_.push_back(&student);
return true;
}
void removeStudent(Student& student) {
students_.erase(std::remove(students_.begin(), students_.end(), &student),
students_.end());
}
void getInfo() const {
std::string prof = professor_ ? "Prof. " + professor_->getName() : "TBD";
std::string names;
for (const Student* s : students_) {
names += (names.empty() ? "" : ", ") + s->getName();
}
std::printf(" %s: %s | Professor: %s | Students: %s\n", code_.c_str(),
title_.c_str(), prof.c_str(), names.c_str());
}
static std::string titles(const std::vector<Course*>& courses) {
std::string out;
for (const Course* c : courses) {
out += (out.empty() ? "" : ", ") + c->getTitle();
}
return out;
}
private:
std::string code_;
std::string title_;
int maxCapacity_;
Professor* professor_ = nullptr; // association: its professor
std::vector<Student*> students_; // association: its students
};
void Student::enroll(Course& course) {
if (std::find(courses_.begin(), courses_.end(), &course) != courses_.end()) {
return;
}
if (!course.addStudent(*this)) {
std::printf(" %s could not enroll: %s is full\n", name_.c_str(),
course.getTitle().c_str());
return;
}
courses_.push_back(&course);
std::printf(" %s enrolled in %s\n", name_.c_str(), course.getTitle().c_str());
}
void Student::drop(Course& course) {
auto it = std::find(courses_.begin(), courses_.end(), &course);
if (it != courses_.end()) {
courses_.erase(it);
course.removeStudent(*this);
std::printf(" %s dropped %s\n", name_.c_str(), course.getTitle().c_str());
}
}
void Student::listCourses() const {
std::printf(" %s's courses: %s\n", name_.c_str(),
Course::titles(courses_).c_str());
}
void Professor::assignCourse(Course& course) {
if (std::find(courses_.begin(), courses_.end(), &course) != courses_.end()) {
return;
}
if (Professor* old = course.getProfessor()) {
std::vector<Course*>& list = old->courses_;
list.erase(std::remove(list.begin(), list.end(), &course), list.end());
}
courses_.push_back(&course);
course.setProfessor(this);
std::printf(" Prof. %s assigned to %s\n", name_.c_str(),
course.getTitle().c_str());
}
void Professor::listCourses() const {
std::printf(" Prof. %s teaches: %s\n", name_.c_str(),
Course::titles(courses_).c_str());
}
int main() {
// Each object is made on its own; the associations only connect them
Student alice("Alice");
Student bob("Bob");
Professor smith("Smith");
Professor jones("Jones");
Course cs101("CS101", "Data Structures");
Course cs201("CS201", "Algorithms");
Course cs301("CS301", "Compilers Seminar", 1);
std::printf("Linking:\n");
smith.assignCourse(cs101);
smith.assignCourse(cs201);
alice.enroll(cs101);
alice.enroll(cs301);
bob.enroll(cs101);
bob.enroll(cs301);
std::printf("Following the links:\n");
smith.listCourses();
bob.listCourses();
cs101.getInfo();
cs301.getInfo();
std::printf("Changing the links:\n");
jones.assignCourse(cs201);
alice.drop(cs101);
smith.listCourses();
jones.listCourses();
cs101.getInfo();
alice.listCourses();
return 0;
}class Student {
private readonly courses: Course[] = []; // association: its courses
constructor(private readonly name: string) {}
getName(): string {
return this.name;
}
// Both sides change together: the course takes the student, or nothing changes
enroll(course: Course): void {
if (this.courses.includes(course)) {
return;
}
if (!course.addStudent(this)) {
console.log(` ${this.name} could not enroll: ${course.getTitle()} is full`);
return;
}
this.courses.push(course);
console.log(` ${this.name} enrolled in ${course.getTitle()}`);
}
// Dropping ends the link on both sides; the course itself goes on
drop(course: Course): void {
const i = this.courses.indexOf(course);
if (i >= 0) {
this.courses.splice(i, 1);
course.removeStudent(this);
console.log(` ${this.name} dropped ${course.getTitle()}`);
}
}
listCourses(): void {
console.log(` ${this.name}'s courses: ${Course.titles(this.courses)}`);
}
}
class Professor {
private readonly courses: Course[] = []; // association: the courses taught
constructor(private readonly name: string) {}
getName(): string {
return this.name;
}
// A course has one professor: a new one takes it off the old professor's list
assignCourse(course: Course): void {
if (this.courses.includes(course)) {
return;
}
const old = course.getProfessor();
if (old) {
old.courses.splice(old.courses.indexOf(course), 1);
}
this.courses.push(course);
course.setProfessor(this);
console.log(` Prof. ${this.name} assigned to ${course.getTitle()}`);
}
listCourses(): void {
console.log(` Prof. ${this.name} teaches: ${Course.titles(this.courses)}`);
}
}
class Course {
private professor: Professor | null = null; // association: its professor
private readonly students: Student[] = []; // association: its students
constructor(
private readonly code: string,
private readonly title: string,
private readonly maxCapacity = 30,
) {}
getTitle(): string {
return this.title;
}
getProfessor(): Professor | null {
return this.professor;
}
setProfessor(professor: Professor): void {
this.professor = professor;
}
addStudent(student: Student): boolean {
if (this.students.length >= this.maxCapacity) {
return false;
}
this.students.push(student);
return true;
}
removeStudent(student: Student): void {
this.students.splice(this.students.indexOf(student), 1);
}
getInfo(): void {
const prof = this.professor ? `Prof. ${this.professor.getName()}` : "TBD";
const names = this.students.map((s) => s.getName()).join(", ");
const head = ` ${this.code}: ${this.title} | Professor: ${prof}`;
console.log(`${head} | Students: ${names}`);
}
static titles(courses: Course[]): string {
return courses.map((c) => c.getTitle()).join(", ");
}
}
// Each object is made on its own; the associations only connect them
const alice = new Student("Alice");
const bob = new Student("Bob");
const smith = new Professor("Smith");
const jones = new Professor("Jones");
const cs101 = new Course("CS101", "Data Structures");
const cs201 = new Course("CS201", "Algorithms");
const cs301 = new Course("CS301", "Compilers Seminar", 1);
console.log("Linking:");
smith.assignCourse(cs101);
smith.assignCourse(cs201);
alice.enroll(cs101);
alice.enroll(cs301);
bob.enroll(cs101);
bob.enroll(cs301);
console.log("Following the links:");
smith.listCourses();
bob.listCourses();
cs101.getInfo();
cs301.getInfo();
console.log("Changing the links:");
jones.assignCourse(cs201);
alice.drop(cs101);
smith.listCourses();
jones.listCourses();
cs101.getInfo();
alice.listCourses();using System;
using System.Collections.Generic;
using System.Linq;
public class Student
{
private readonly List<Course> courses = new(); // association: its courses
public Student(string name)
{
Name = name;
}
public string Name { get; }
// Both sides change together: the course takes the student, or nothing changes
public void Enroll(Course course)
{
if (courses.Contains(course))
{
return;
}
if (!course.AddStudent(this))
{
Console.WriteLine($" {Name} could not enroll: {course.Title} is full");
return;
}
courses.Add(course);
Console.WriteLine($" {Name} enrolled in {course.Title}");
}
// Dropping ends the link on both sides; the course itself goes on
public void Drop(Course course)
{
if (courses.Remove(course))
{
course.RemoveStudent(this);
Console.WriteLine($" {Name} dropped {course.Title}");
}
}
public void ListCourses()
{
Console.WriteLine($" {Name}'s courses: {Course.Titles(courses)}");
}
}
public class Professor
{
private readonly List<Course> courses = new(); // association: the courses taught
public Professor(string name)
{
Name = name;
}
public string Name { get; }
// A course has one professor: a new one takes it off the old professor's list
public void AssignCourse(Course course)
{
if (courses.Contains(course))
{
return;
}
course.Professor?.courses.Remove(course);
courses.Add(course);
course.Professor = this;
Console.WriteLine($" Prof. {Name} assigned to {course.Title}");
}
public void ListCourses()
{
Console.WriteLine($" Prof. {Name} teaches: {Course.Titles(courses)}");
}
}
public class Course
{
private readonly string code;
private readonly int maxCapacity;
private readonly List<Student> students = new(); // association: its students
public Course(string code, string title, int maxCapacity = 30)
{
this.code = code;
Title = title;
this.maxCapacity = maxCapacity;
}
public string Title { get; }
public Professor? Professor { get; set; } // association: its professor
public bool AddStudent(Student student)
{
if (students.Count >= maxCapacity)
{
return false;
}
students.Add(student);
return true;
}
public void RemoveStudent(Student student)
{
students.Remove(student);
}
public void GetInfo()
{
string prof = Professor != null ? $"Prof. {Professor.Name}" : "TBD";
string names = string.Join(", ", students.Select(s => s.Name));
Console.WriteLine($" {code}: {Title} | Professor: {prof} | Students: {names}");
}
public static string Titles(List<Course> courses) =>
string.Join(", ", courses.Select(c => c.Title));
}
public static class UniversityDemo
{
public static void Main()
{
// Each object is made on its own; the associations only connect them
var alice = new Student("Alice");
var bob = new Student("Bob");
var smith = new Professor("Smith");
var jones = new Professor("Jones");
var cs101 = new Course("CS101", "Data Structures");
var cs201 = new Course("CS201", "Algorithms");
var cs301 = new Course("CS301", "Compilers Seminar", 1);
Console.WriteLine("Linking:");
smith.AssignCourse(cs101);
smith.AssignCourse(cs201);
alice.Enroll(cs101);
alice.Enroll(cs301);
bob.Enroll(cs101);
bob.Enroll(cs301);
Console.WriteLine("Following the links:");
smith.ListCourses();
bob.ListCourses();
cs101.GetInfo();
cs301.GetInfo();
Console.WriteLine("Changing the links:");
jones.AssignCourse(cs201);
alice.Drop(cs101);
smith.ListCourses();
jones.ListCourses();
cs101.GetInfo();
alice.ListCourses();
}
}package main
import (
"fmt"
"slices"
"strings"
)
// Each type keeps pointers to the others: it knows them and owns none of them
type Student struct {
name string
courses []*Course // association: its courses
}
func NewStudent(name string) *Student {
return &Student{name: name}
}
// Both sides change together: the course takes the student, or nothing changes
func (s *Student) Enroll(c *Course) {
if slices.Contains(s.courses, c) {
return
}
if !c.AddStudent(s) {
fmt.Printf(" %s could not enroll: %s is full\n", s.name, c.title)
return
}
s.courses = append(s.courses, c)
fmt.Printf(" %s enrolled in %s\n", s.name, c.title)
}
// Dropping ends the link on both sides; the course itself goes on
func (s *Student) Drop(c *Course) {
if i := slices.Index(s.courses, c); i >= 0 {
s.courses = slices.Delete(s.courses, i, i+1)
c.RemoveStudent(s)
fmt.Printf(" %s dropped %s\n", s.name, c.title)
}
}
func (s *Student) ListCourses() {
fmt.Printf(" %s's courses: %s\n", s.name, Titles(s.courses))
}
type Professor struct {
name string
courses []*Course // association: the courses taught
}
func NewProfessor(name string) *Professor {
return &Professor{name: name}
}
// A course has one professor: a new one takes it off the old professor's list
func (p *Professor) AssignCourse(c *Course) {
if slices.Contains(p.courses, c) {
return
}
if old := c.professor; old != nil {
old.courses = slices.DeleteFunc(old.courses, func(x *Course) bool { return x == c })
}
p.courses = append(p.courses, c)
c.professor = p
fmt.Printf(" Prof. %s assigned to %s\n", p.name, c.title)
}
func (p *Professor) ListCourses() {
fmt.Printf(" Prof. %s teaches: %s\n", p.name, Titles(p.courses))
}
type Course struct {
code string
title string
maxCapacity int
professor *Professor // association: its professor
students []*Student // association: its students
}
func NewCourse(code, title string, maxCapacity int) *Course {
return &Course{code: code, title: title, maxCapacity: maxCapacity}
}
func (c *Course) AddStudent(s *Student) bool {
if len(c.students) >= c.maxCapacity {
return false
}
c.students = append(c.students, s)
return true
}
func (c *Course) RemoveStudent(s *Student) {
c.students = slices.DeleteFunc(c.students, func(x *Student) bool { return x == s })
}
func (c *Course) GetInfo() {
prof := "TBD"
if c.professor != nil {
prof = "Prof. " + c.professor.name
}
names := make([]string, 0, len(c.students))
for _, s := range c.students {
names = append(names, s.name)
}
fmt.Printf(" %s: %s | Professor: %s | Students: %s\n", c.code, c.title, prof,
strings.Join(names, ", "))
}
func Titles(courses []*Course) string {
titles := make([]string, 0, len(courses))
for _, c := range courses {
titles = append(titles, c.title)
}
return strings.Join(titles, ", ")
}
func main() {
// Each object is made on its own; the associations only connect them
alice := NewStudent("Alice")
bob := NewStudent("Bob")
smith := NewProfessor("Smith")
jones := NewProfessor("Jones")
cs101 := NewCourse("CS101", "Data Structures", 30)
cs201 := NewCourse("CS201", "Algorithms", 30)
cs301 := NewCourse("CS301", "Compilers Seminar", 1)
fmt.Println("Linking:")
smith.AssignCourse(cs101)
smith.AssignCourse(cs201)
alice.Enroll(cs101)
alice.Enroll(cs301)
bob.Enroll(cs101)
bob.Enroll(cs301)
fmt.Println("Following the links:")
smith.ListCourses()
bob.ListCourses()
cs101.GetInfo()
cs301.GetInfo()
fmt.Println("Changing the links:")
jones.AssignCourse(cs201)
alice.Drop(cs101)
smith.ListCourses()
jones.ListCourses()
cs101.GetInfo()
alice.ListCourses()
}It prints:
Linking:
Prof. Smith assigned to Data Structures
Prof. Smith assigned to Algorithms
Alice enrolled in Data Structures
Alice enrolled in Compilers Seminar
Bob enrolled in Data Structures
Bob could not enroll: Compilers Seminar is full
Following the links:
Prof. Smith teaches: Data Structures, Algorithms
Bob's courses: Data Structures
CS101: Data Structures | Professor: Prof. Smith | Students: Alice, Bob
CS301: Compilers Seminar | Professor: TBD | Students: Alice
Changing the links:
Prof. Jones assigned to Algorithms
Alice dropped Data Structures
Prof. Smith teaches: Data Structures
Prof. Jones teaches: Algorithms
CS101: Data Structures | Professor: Prof. Smith | Students: Bob
Alice's courses: Compilers Seminar
Read the output against the fields. After the linking calls, Smith's list holds both courses and each course names Smith; CS101 lists Alice and Bob, and each of them lists CS101. Bob's request for CS301 never touches Bob's list, because the course said no first, so Bob's courses are Data Structures only. When Jones takes CS201, it leaves Smith's list in the same call, so Smith teaches Data Structures only and Jones teaches Algorithms, which is also what CS201's own professor field says. Alice's drop removes the link from both ends, and both objects carry on: CS101 keeps running with Bob, and Alice still takes the Compilers Seminar.
Association and the Other Relationships
Association is the general relationship. The next three lessons look at the others, and the same university gives each its example:
| Relationship | What it says | How UML draws it |
|---|---|---|
| Association | Each object can keep a reference to the other, and each lives on its own: a professor and the courses they teach | A solid line |
| Aggregation | A whole and its parts, where a part can live without the whole: a department and its professors | A solid line with a hollow diamond at the whole |
| Composition | A whole that is responsible for its parts, which go when it goes: a university and its departments | A solid line with a filled diamond at the whole |
| Dependency | One class uses another for a while without keeping it: a student who prints a transcript on a printer | A dashed arrow |
Aggregation and composition are associations with one end marked. For composition the specification gives a firm rule: "If a composite object is deleted, all of its part instances that are objects are deleted with it." For aggregation it gives none: "Precise semantics of shared aggregation varies by application area and modeler." The course uses aggregation for parts that can live on without their whole, as Aggregation — Has-A with Independent Lifecycle explains, and Composition — Has-A with Dependent Lifecycle takes up the filled diamond.
Dependency is not a kind of association. It is a relationship of its own: "A Dependency is shown as a dashed arrow between two model Elements." Dependency — Objects That Use Each Other covers it.
Common Mistakes
Mistake 1: calling every method call an association. Suppose Student has a method print_transcript(printer) that uses the printer and never stores it. The student depends on the printer for that one call, and that is a dependency. An association needs a field, so that the reference is kept and can be used again later.
Mistake 2: changing one side of a two-way link. Updating both fields is not enough when the other side can say no, or when a third object also holds the link. A version of these classes that leaves those two cases out shows both faults when it runs. Its enroll added the course to the student's list first and then called add_student, which turns a student away when the course is full, and nobody checked the answer. With CS301 full, it printed "Bob enrolled in Compilers Seminar", Bob's list held CS301, and CS301's students were Alice alone. When Bob later dropped CS301, the Python version stopped with a ValueError ("list.remove(x): x not in list"), because the course had never taken Bob; the Java version carried on with no error. Its assign_course set the course's new professor but left the course on the old professor's list, so after Jones took Algorithms, both Smith and Jones listed it.
The listing above avoids both. Ask the side that can refuse before changing anything, and when a link moves to a new object, take it off the old one in the same method.
Mistake 3: a plain association where the part cannot live without the whole. An OrderItem means nothing without its Order, and it should go when the order goes. That is composition, which Composition — Has-A with Dependent Lifecycle explains.
Key Takeaways
- An association is a reference that one object keeps to another in a field. Neither object makes or owns the other, and both can exist without the link.
- An association can go one way or both ways. A two-way association is two references, one in each object, and a change must update both.
- Multiplicity counts the objects at each end of a link, and it tells you the field: a single reference when the upper limit is 1, a list when it is higher.
- In a class diagram an association is a solid line, with the end names and multiplicities at its ends, and an open arrowhead only where one side alone can follow it.
- Aggregation — Has-A with Independent Lifecycle comes next: an association between a whole and parts that live on without it.