To pick up where we left off our Class/ Object Relations discussion, we are going to continue with Association.
Association
We are speaking of an Association when one object, say Object B uses or has an interaction with Object A. There may be cases where Object B interacts with Object A and vice versa. In such a scenario we are dealing with a Bidirectional Association.
Note: Association is used to represent fields (constants, variables) in a class
One Way Association
Teacher Object Knows About Student Object
Class Teacher Depends On Class Student
Bi-directional Association
Teacher Object Knows About Student Object
Class Teacher Depends On Class Student
Student Object Knows About Teacher Object
Class Student Depends On Class Teacher
Disclaimer: The following code examples display combined example of Dependency and Association trying to solidify your understanding of the difference between those topics.
Pseudo Code
//Course Class
class Course is
courseTitle: String
method constructor(String courseTitle) is
this.courseTitle = courseTitle
method courseId(): String is
return this.courseTitle
//Student Class
class Student is
name: String
lastName: String
age: Integer
method constructor(String name, String lastName, Integer age) is
this.name = name
this.latsName = lastName
this.age = age
method knows(Course course): String is //Student has a Dependency with class Course
print(course.courseId())
//Teacher Class
class Teacher is
//class Teacher has an association with class Student
//A Teacher object knows about Student Objects
//class Professor depends on class Student
private students: Student //Association
method examen(Course course) is //Professor has a Dependency with class Course
this.student.knows(course)
Swift Code
import Foundation
class Course {
private var courseTitle: String
init( _ courseTitle: String) {
self.courseTitle = courseTitle
}
func courseId() -> String {
return courseTitle
}
}
class Student {
let name: String
let lastName: String
let age: Int
init(name: String, lastName: String, age: Int) {
self.name = name
self.lastName = lastName
self.age = age
}
func knows( _ course: Course) { //Dependency
print(course.courseId())
}
}
// Teacher ––––––––> Student
class Teacher {
//class Teacher has an association with class Student
//A Teacher object knows about Student Objects
//class Professor depends on class Student
private var student: Student //Association
init( _ student: Student) {
self.student = student
}
func examen( _ course: Course ) { //Dependency
self.student.knows(course)
}
}
let newStudent = Student(name: "Joseph", lastName: "Doe", age: 24)
let teacher = Teacher(newStudent)
let course = Course("Algebra")
teacher.examen(course) //Algebra