I'm learning about composition in OOP and UML. If a Course is composed of Exam objects, can Student and Professor objects also reference the Course? Would those references prevent the Course and its exams from being deleted?
Can other classes reference the whole in a composition relationship?
Answers
Yes. Being the whole in a composition does not prevent Course from having other associations. A Student or Professor can reference a Course without becoming its owner in the Course and Exam composition.
Composition describes the relationship between the whole and its parts. It doesn't mean the whole has to be isolated from the rest of your model.
Reply to this answer
The deletion question depends on the language and how you manage references. In a garbage collected language, a strong reference from a reachable Student can keep the Course reachable. If the Course still holds its Exams, those objects can remain reachable too.
That is separate from the UML relationship. A composition diagram does not automatically make your program delete anything. If your application explicitly removes a course, you need to decide what happens to references held elsewhere and how its exams are removed or invalidated.
Reply to this answer
A class can also be a part in one composition and a whole in another. For example, if your domain really treats a Course as an inseparable part of some larger object, it could own Exams while itself being owned by that larger object.
That's a modeling choice, not a consequence of Student or Professor merely referencing it. A reference alone doesn't tell you whether the relationship is composition.
Reply to this answer
One thing to check is whether composition fits Exam in your particular model. Having a collection of exams is not enough by itself to establish composition. Think about whether an exam belongs exclusively to that course and whether it should cease to exist when the course is removed.
A course having zero or many exams is a separate multiplicity question. Either can be represented without deciding ownership from the collection alone.
Reply to this answer
Add your answer
Answers are reviewed before publication.
!!almost.a.solution:
So deleting a course from the application's data and the object being reclaimed from memory aren't necessarily the same event?
TAP_once_then_wait:
Right. An application can mark or remove a course while an in-memory object is still referenced. The exact behavior depends on the implementation.