Composition allows you to specify very different kinds of relationships between classes. This is sometimes also called containment. If you’re building a racing game and have a car class and a wheel class, you wouldn’t want to say that cars are wheels but instead that cars have wheels. Proper use of composition will even allow you to substitute what kind of wheels your cars have. This can not only simplify your designs but make your code easier to test.
You want to make sure that inheritance is right for your situation before using it and this episode will give you another option to consider.
One reason to use composition is to hide certain methods on another class and just expose a limited set of functionality. Or maybe you want to be able to perform some extra validation. Instead of inheriting from the other class, you can contain an instance of the other class inside your new class and have your own methods that do whatever you need. Your methods could call methods on the embedded class to do some or all of the real work. Outside code will have no knowledge that you’re using the other class for this.
You can also expose a collection of instances of the other class. the introduction to this episode mentioned cars and wheels. Your car class can contain however many wheels you need and can expose as much or as little flexibility to change this to outside code as you want. If you allow outside code to provide new wheels, then you also provide some real flexibility to test your code. This is because your test code can supply wheels that are specifically designed to test certain conditions or to record information that can be analyzed later.
You can also use containment to simplify your class hierarchies and move what used to require extra classes into data. This allows you to extend your application at runtime and can be used to modify your program after it’s been written. You do lose the ability to easily change behavior. Overriding methods is one of the main benefits of inheritance so going with data instead makes it harder to change behavior.
In the end, the choice is yours. There is no one right answer for all scenarios.