Composition &
Aggregation
Muhammad Abdul Jabbar
Composition vs Inheritance
• Inheritance and composition are two programming techniques.
• The developers use to establish relationships between classes and objects.
• Inheritance derives one class from another, composition defines a class as
the sum of its parts.
• If a class B is derived by inheritance from a class A, we can say that “B is a kind of A.”
• This is because B has all the characteristics of A, and in addition some of its own.
• Inheritance is often called a “kind of” or “is a” relationship.
• A person is a human.
• A cat is an animal.
• A car is a vehicle.
Composition vs Inheritance
• Composition is called a “has a” relationship. (one object "has" (or is part of) another object”
• The book is part of the library.
• A car has a battery (a battery is part of a car).
• A person has a hand (a hand is part of a person).
• Composition may occur when one object is an attribute of another. Here’s a case where an object
of class A is an attribute of class B:
A
{
};
class B
{
A objA; // define objA as an object of class A
};
Association vs Aggregation vs
Composition
• Aggregation and Composition are subsets of association meaning they are
specific cases of association.
• In both aggregation and composition object of one class "owns" object of
another class. But there is a subtle difference:
• Aggregation implies a relationship where the child can exist independently of the
parent. Example: Class (parent) and Student (child). Delete the Class and the
Students still exist.
• Composition implies a relationship where the child cannot exist independent of the
parent. Example: House (parent) and Room (child). Rooms don't exist separate to a
House.
• It has all the characteristics of aggregation, plus two more:
• The part may belong to only one whole.
• The lifetime of the part is the same as the lifetime of the whole.