Inheritance versus Composition

Inheritance versus Composition

An example of composition might be a classthat is used by another class:So, a”has a” (an)

The famous Design Patterns: Elements of Reusable Object-Oriented Software book has suggested favoring composition over inheritance. The composition version passes the into the initialization of the :

After that, theobject can be used in code that looks exactly the same as it was for the inheritance version:The final print statement would yield:

But, as Ortiz pointed out, there is lots that gets for free when it uses inheritance that needs to be explicitly added to the class when it uses composition. Many methods (e.g. , , , etc.) that came with the via inheritance needed to be implemented for the class when it uses composition.

Source: lwn.net