Composition

In general terms, composition allows a class to contain an object instance of another class.
Composition can be denoted as being an "as a part" or a "has a" relationship between classes.
In the composition approach, the derived class becomes the front-end class and the base class becomes the back-end class.
The composition approach provides stronger encapsulation than inheritance, because a change to a back-end class does not necessarily break any code that relies on the front-end class.
The main advantages of composition is, with carefully designed interfaces we can change references of back end classes at runtime.


Think of inheritance when there is a relationship between two things.

A car "is a" vehicle, a person "is a" mammal 

Think of composition when there something has a relationship with something else.

A car "has an" engine, a person "has a" name 

Inheritance vs Composition

In inheritance, there is an image of the base class in the derived class object, so the image of the base class is created when the derived class object is created.
Composition allows late creation of the backend class object until and unless they are not really required.


In inheritance the base class remains a part of the derived class object throughout the life of the derived class.
In composition, life of the backend class is independent and we can change back end object dynamically.


Inheritance is static binding (compile time binding)
Composition is dynamic binding (run time binding)


Inheritance comes with polymorphism.
Composition has no concept of polymorphism


In inheritance, there is a single invocation of an inherited base class so there is no extra cost for invocation.
In composition the explicit method invocation (forwarding or delegation) has a performance cost (note that performance depends on many factors).


In inheritance a change in the base class interface cannot ripple down the inheritance hierarchy to a derived class.
In composition it is easy to change the interface of a back-end class and front-end class


In inheritance it is not required to implement all base class methods within the derived class.
In composition, all methods provided by composed classes must be implemented in the front end class.


In inheritance the derived class and base class interfaces are tightly coupled.
In composition the front-end and back-end interfaces are loosely coupled.



It is easier to add new derived classes in inheritance than to add new front-end class in composition.



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrev