Composition Vs Inheritance

Posted on

I will be using the world class to mean class, struct, object or any king of data thing that encapsulates functionality.

Inheritance acquires functionality from its parent class usually via the extends keyword. This method is modelled off genealogy. Think real life parents and the characteristics that are inherited by their child.

In Composition a class acquires its functionality from the classes that it is composed of. Think Frankensteins monster. Think an arm stitched on that has a special ability to catch, legs from a class that is particularly good at running. The torso of Arnold Schwarzenegger. You get the picture.

The inheritance data model is tightly coupled. Changing functionality in the parent class, could alter will alter the functionality of the child.

On the other hand composition is loosely coupled as parts can be chopped and changed with less chance of breaking the code. As long as the new part has all the functionality as the last. Your class will continue to have the same methods it has always had.