What are object composition and aggregation?

Object composition in OOP refers to combining two or more different classes with purpose of creating new, more complex class. Usually it looks like an object that contains another object. "Сontains" means object has reference to other one.

In case of composition, an object "owns" another object, rather than just use it, which means if main object will be destroyed, all internal objects should be destroyed as well. Internal objects usually are necessary parts of the main object, so the main object can't exist without them and internal objects don't have much sense on their own. In case of aggregation, which is a closely related concept to composition, you can say an internal object is a part of the main object, but is still independent and can exists on its own. Note this difference.

Example of object composition and aggregation

Let's say you have Vehicle class in your application. It should has Engine, Body and Wheels in it.

public class Vehicle
{
    private Engine enginePart;
    private Body bodyPart;
    private Wheel[] wheelsPart;

    public Vehicle(Engine engine, Body body, Wheel[] wheels)
    {
        this.enginePart = engine;
        this.bodyPart = body;
        this.wheelsPart = wheels;
    }
}

Vehicle owns its parts and can't function without them and Engine, Body and Wheel don't have much use on their own. If you, let's say, call Explode method on Vehicle, Vehicle object will be destroyed as well as its parts. This is what we call object composition.

Now let's imagine, that you have Bank class, which has array of Customer objects in it.

public class Bank
{
    private Customer[] customersList;

    public Vehicle(Customer[] customers)
    {
        this.customersList = customers;
    }
}

Bank contains Customers and can exists without them (but, probably, not generate profit for its owner). Customer can exist without Bank, he can be listed as client of CarService or Clinic, for example. If you call Explode method on Bank (wow, sounds criminal), Bank will be destroyed, but not Customers. This is object aggregation.

Composition and aggregation

Image source: atomicobject.com

Short answer

  • Object composition refers to combining two or more objects to create new one. "Class A owns class B" relationship established between objects.
  • Object aggregation means same as composition, but establishes "Class A contains class B" relationship type.
  • Inheritance establishes "IS-A" relationship between classes and composition/aggregation is "HAS-A" relationship.
  • Prefer composition over inheritance, since it has a lot of advantages.

Comments