Composition is when a class offers some functionality by instantiating a (possibly internal) class which already implements this functionality, instead of inheriting from that class.
So, for example, if you have a class which models a ship, and you are now being told that your ship should offer a helipad, it is not natural to derive your ship from a helipad, (duh!) instead, you should have your ship contain a helipad class and expose it via some Ship.getHelipad()
method.
In years of old (a decade or so ago) people used to view inheritance as a quick and easy way to aggregate functionality, so there were many examples of the "ship inheriting from helipad" kind, which were, of course, very lame.
But the "Favor Composition over Inheritance" dictum has been carefully worded as to make it clear that this is just a suggestion, not a rule. The author of the dictum was careful enough to refrain from saying something like "thou shalt never use inheritance, only composition". This is basically bringing to the attention of the software engineering community the fact that inheritance has been overused, while in many cases, composition produces more clear, elegant, and maintainable designs than inheritance.
So, essentially, the "Favor Composition over Inheritance" dictum is suggesting that whenever you are faced with the "to inherit or to compose?" question, you should think hard what's the most suitable strategy, and that most chances are that the most suitable strategy will turn out to be composition, not inheritance.
But since this is not a rule, you should also keep in mind that there are many cases where inheritance is more natural. If you use composition there where you should have used inheritance, many evils will befall your code.
To go back to the ship example, if your ship needs to offer an interface for interacting with a FloatingMachine
, then it is more natural to derive it from an abstract FloatingMachine
class, which might very possibly in turn be derived from another abstract Machine
class.
Here is the rule of thumb for the answer to the composition vs. inheritance question:
Does my class have an "is a" relationship to the interface that it
needs to expose? If yes, use inheritance. If not, use composition.
A ship "is a" floating machine, and a floating machine "is a" machine. So, inheritance is perfectly fine for those. But a ship is not, of course, a helipad. So it better compose the functionality of the helipad.