Dependency vs Composition | Sololearn: Learn to code for FREE!


Dependency vs Composition

I'm confused between the differences in the two of them, as I see both of them naket an instance of another class inside them... So how are they different?


9/19/2021 5:38:21 PM


3 Answers

New Answer


The two are often very similar. The main difference you'll usually see is that with Dependency, the instance creation of the other class will take place outside of the encapsulating class and is passed in, usually via the classes constructor. With Composition, the instance of the other class is created within the encapsulating class itself, again usually in the constructor, but may also be done within a method or as a field.


Here, maybe this will explain things better than my attempt.


ChaoticDawg but then dependency looks like an aggregation since you do the same thing you described for dependency