Junior — Middle
Can you explain the concept of association in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming, an association is a relationship between two classes where objects of one class can interact with objects of another class. It is a 'has' or 'connected to' relationship. An association can be unidirectional (one class knows about the other) or bidirectional (both classes know about each other).
For example, a Student class can be associated with a Course class if the student is enrolled in a course. In this case, the student and the course are separate objects, but there is a connection between them.
class Student {
var name: String
var courses: [Course] = []
init(name: String) {
self.name = name
}
}
class Course {
var title: String
init(title: String) {
self.title = title
}
}
let math = Course(title: "Mathematics")
let student = Student(name: "Ivan")
student.courses.append(math)
Here, Student is associated with Course through an array of courses. The association does not imply ownership or lifecycle, unlike composition or aggregation.