After seeing some of the issues that arise from not correctly using inheritance, the next logical step is to look at a principle that avoids inheritance altogether. This principle is the Prefer Composition over Inheritance principle.
Composition over Inheritance means that classes should be composed of instances of other classes to implement behavior or attributes instead of inheriting behavior or attributes from a base class. This means that a class would contain one or more fields that are references to other classes, and the current class delegates work to them.
Let's look at a slightly different design for
Invoice. An invoice could be considered simply as a collection of
InvoiceLineItems. As such, we could implement ...