#688 – Aggregation, Composition and Containment
October 9, 2012 Leave a comment
The idea of containment in object-oriented programming is the idea that an outer class contains an instance of another class and allows access to the contained object through its own methods.
Aggregation is one form of containment where the contained object can exist independently from the outer object. For example, a Family object might contain an instance of a Dog object, representing a dog that the family owns.
public class Family { List<Dog> OurDog { get; set; } void AcquireDog(Dog d) { OurDog.Add(d); } }
Composition is a type of containment where the contained object is created and exists entirely within the object that contains it. It ceases to exist when the containing object is destroyed. For example a Dog is composed of an instance of a DogName object (among other things). You can’t have an instance of a DogName without a Dog.