Association
Classes that know about each other and can communicate.
Association is a relationship where one class knows about another class and can use its services. It’s a “uses-a” or “knows-a” relationship where classes can exist independently.
What is Association?
Section titled “What is Association?”Association represents a relationship where:
- Classes know about each other
- Classes can communicate with each other
- Classes have independent lifecycles
- Usually implemented with references or pointers
Key Characteristics
Section titled “Key Characteristics”- Independent existence - Both classes can exist without each other
- Communication - Classes can call each other’s methods
- References - One class holds a reference to another
- Weaker than composition - No ownership implied
Unidirectional Association
Section titled “Unidirectional Association”One class knows about another, but not vice versa.
class Teacher: def __init__(self, name: str): self.name = name self.courses = [] # Association with Course
def teach(self, course): """Teacher uses Course""" self.courses.append(course) return f"{self.name} is teaching {course.name}"
class Course: def __init__(self, name: str): self.name = name
# Usageteacher = Teacher("Dr. Smith")course = Course("Python Programming")
print(teacher.teach(course)) # "Dr. Smith is teaching Python Programming"# Course doesn't know about Teacherpublic class Teacher { private String name; private java.util.List<Course> courses; // Association with Course
public Teacher(String name) { this.name = name; this.courses = new java.util.ArrayList<>(); }
// Teacher uses Course public String teach(Course course) { courses.add(course); return name + " is teaching " + course.getName(); }}
public class Course { private String name;
public Course(String name) { this.name = name; }
public String getName() { return name; }}
// Usagepublic class Main { public static void main(String[] args) { Teacher teacher = new Teacher("Dr. Smith"); Course course = new Course("Python Programming");
System.out.println(teacher.teach(course)); // "Dr. Smith is teaching Python Programming" // Course doesn't know about Teacher }}Bidirectional Association
Section titled “Bidirectional Association”Both classes know about each other.
class Student: def __init__(self, name: str): self.name = name self.courses = [] # Student knows about courses
def enroll(self, course): self.courses.append(course) course.students.append(self) # Course knows about student
class Course: def __init__(self, name: str): self.name = name self.students = [] # Course knows about students
# Usagestudent = Student("Alice")course = Course("Data Structures")
student.enroll(course)print(f"{student.name} enrolled in {course.name}")print(f"{course.name} has {len(course.students)} student(s)")public class Student { private String name; private java.util.List<Course> courses; // Student knows about courses
public Student(String name) { this.name = name; this.courses = new java.util.ArrayList<>(); }
public void enroll(Course course) { courses.add(course); course.addStudent(this); // Course knows about student }
public String getName() { return name; }}
public class Course { private String name; private java.util.List<Student> students; // Course knows about students
public Course(String name) { this.name = name; this.students = new java.util.ArrayList<>(); }
public void addStudent(Student student) { students.add(student); }
public String getName() { return name; }
public int getStudentCount() { return students.size(); }}
// Usagepublic class Main { public static void main(String[] args) { Student student = new Student("Alice"); Course course = new Course("Data Structures");
student.enroll(course); System.out.println(student.getName() + " enrolled in " + course.getName()); System.out.println(course.getName() + " has " + course.getStudentCount() + " student(s)"); }}Visual Representation
Section titled “Visual Representation”Real-World Example: Library System
Section titled “Real-World Example: Library System”class Book: def __init__(self, isbn: str, title: str): self.isbn = isbn self.title = title self.available = True
class Loan: def __init__(self, member, book): self.member = member # Association - references Member self.book = book # Association - references Book self.borrow_date = None self.return_date = None
def borrow(self): if self.book.available: self.book.available = False self.borrow_date = "2024-01-01" return f"{self.member.name} borrowed {self.book.title}" return "Book not available"
class Member: def __init__(self, name: str, member_id: str): self.name = name self.member_id = member_id
def borrow_book(self, book): loan = Loan(self, book) # Creates association return loan.borrow()
# Usagemember = Member("Alice", "M001")book = Book("12345", "Python Guide")
print(member.borrow_book(book)) # "Alice borrowed Python Guide"public class Book { private String isbn; private String title; private boolean available;
public Book(String isbn, String title) { this.isbn = isbn; this.title = title; this.available = true; }
public String getTitle() { return title; }
public boolean isAvailable() { return available; }
public void setAvailable(boolean available) { this.available = available; }}
public class Loan { private Member member; // Association - references Member private Book book; // Association - references Book private String borrowDate; private String returnDate;
public Loan(Member member, Book book) { this.member = member; this.book = book; }
public String borrow() { if (book.isAvailable()) { book.setAvailable(false); this.borrowDate = "2024-01-01"; return member.getName() + " borrowed " + book.getTitle(); } return "Book not available"; }}
public class Member { private String name; private String memberId;
public Member(String name, String memberId) { this.name = name; this.memberId = memberId; }
public String getName() { return name; }
public String borrowBook(Book book) { Loan loan = new Loan(this, book); // Creates association return loan.borrow(); }}
// Usagepublic class Main { public static void main(String[] args) { Member member = new Member("Alice", "M001"); Book book = new Book("12345", "Python Guide");
System.out.println(member.borrowBook(book)); // "Alice borrowed Python Guide" }}Key Takeaways
Section titled “Key Takeaways”When to Use Association
Section titled “When to Use Association”Use Association when:
- Classes need to communicate with each other
- Classes have independent lifecycles
- One class uses another’s services
- You need flexibility to change relationships
- Classes are loosely coupled
Examples:
- Teacher ↔ Course
- Student ↔ Course
- Order ↔ Product
- Loan ↔ Book
- Customer ↔ Order