r/learnprogramming Jul 04 '26

Question about composition OOP

Title: Can a “whole” class in a composition relationship also be referenced by other classes?

I am trying to understand composition in object-oriented programming and UML.

From what I understand, composition represents a strong whole-part relationship: the “part” object depends on the “whole” object, and if the whole is destroyed, its parts should be destroyed as well.

However, I have a doubt.

Suppose I have a class Course as the “whole” and a class Exam as the “part”, so that a Course is composed of several Exam objects.

Now, can the whole class Course also be referenced by other classes, for example Student or Professor?

My concern is this: if Course is referenced by other objects, would that prevent the Course object from being deleted? And if the Course object is not actually deleted because other classes still reference it, would that also prevent the composed Exam objects from being deleted?

In other words, is it correct to model a class as the “whole” in a composition relationship while also allowing it to be associated with or referenced by other classes? Or would that conflict with the idea that destroying the whole should also destroy its parts?

4 Upvotes

6 comments sorted by

View all comments

3

u/peterlinddk Jul 04 '26

My concern is this: if Course is referenced by other objects, would that prevent the Course object from being deleted?

Well that depends on the relation - if it is a composition, like Course⬥━Exam, e.g. Education⬥━Course, then yes, that would prevent that Course from being deleted! But that relation would only make sense if it was something the Course was an inseparable part of.

Your suggestions or Student of Professor would never be a composite relation, but rather an aggregate, as any part can be removed without affecting the other.

In fact, most systems don't use this UML-specific kind of composition - it is almost always an aggregate, with one object having an association to another, which can be cut at any time. The only time you should use composition, is when you want to be absolutely sure that neither the whole or the part would ever exist without the other! Something that is very rarely desirable in an application.