Composition over inheritance

[3] An implementation of composition over inheritance typically begins with the creation of various interfaces representing the behaviors that the system must exhibit.

An example in C++ follows: Then, suppose we also have these concrete classes: Note that multiple inheritance is dangerous if not implemented carefully because it can lead to the diamond problem.

Due to the C++ language not having a dedicated keyword to declare interfaces, the following C++ example uses inheritance from a pure abstract base class.

For example, an accelerator pedal and a steering wheel share very few common traits, yet both are vital components in a car.

Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members.

Additionally, it avoids problems often associated with relatively minor changes to an inheritance-based model that includes several generations of classes.

For example, in the C# code below, the variables and methods of the Employee base class are inherited by the HourlyEmployee and SalariedEmployee derived subclasses.

Some languages provide specific means to mitigate this: A 2013 study of 93 open source Java programs (of varying size) found that: While there is not huge opportunity to replace inheritance with composition (...), the opportunity is significant (median of 2% of uses [of inheritance] are only internal reuse, and a further 22% are only external or internal reuse).

This diagram shows how the fly and sound behavior of an animal can be designed in a flexible way by using the composition over inheritance design principle. [ 1 ]