Search code examples
javaoopinheritancecomposition

When to use composition and when to use inheritance


Is there a way of telling when to use composition and when to use inheritance in your code.

Example: Let's say we have 4 classes called Computer, MotherBoard, Monitor, Keyboard. I can make computer inherit from the other three classes and I can also declare MotherBoard, Monitor, Keyboard in the field of computer, thus for the second case using composition. Which way is better? Which way is preferred by most developers?


Solution

  • I prefer the inheritance in the following cases:

    • Both classes are in the same logical domain
    • The subclass is a proper subtype of the superclass
    • The superclass’s implementation is necessary or appropriate for the subclass
    • The enhancements made by the subclass are primarily additive.

    Otherwise, the composition is appropriate.

    Note that in this case, the computer is composed of the components you have listed. As a shortcut, I sometimes ask myself the following:

    • Does Computer have a Mouse? If so, then use composition. Notice a computer can have no mouse.
    • Is MacBook a Computer? If so, then use inheritance.

    ... but in general which way is preferred

    In general, the decision should be based on the situation :)