Inheritance vs Composition

Composition vs Inheritance

A lot of junior developers don’t know exactly mean of these and how it’s different.

  • How many ways you can decorate or re-use a code base ?
  • How you can decorate an existed control/class but you need to hide it’s base behavior ?

Let’s understand what’s different between them:

We also have many level of Composition :

Association vs Aggregation vs Composition

The question “What is the difference between association, aggregation, and 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.

Composition Example:

We should be more specific and use the composition link in cases where in addition to the part-of relationship between Class A and Class B – there’s a strong lifecycle dependency between the two, meaning that when Class A is deleted then Class B is also deleted as a result

UML composition example

Aggregation Example:

It’s important to note that the aggregation link doesn’t state in any way that Class A owns Class B nor that there’s a parent-child relationship (when parent deleted all its child’s are being deleted as a result) between the two. Actually, quite the opposite! The aggregation link is usually used to stress the point that Class A instance is not the exclusive container of Class B instance, as in fact the same Class B instance has another container/s.

UML aggregation example

The implementation of Aggregation and Composition usually depend on the your context. It’s not always the same in every object relationship.

In OOP Principle , we have :Composition over Inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class.

This also trade off design, you should consider. Composition will give you flexible but sometime code duplication is exist and inverse , Inheritance sometime hard to flexible because you depend on base structure and behavior but it give you maximize code re-use.

Share
%d bloggers like this: