Have you heard the phrase "prefer composition over inheritance" in design discussions and wondered what does this mean? In this post let's see what actually "prefer composition over inheritance" means.
Inheritance is one of the building blocks of OOPS, we have been taught to use inheritance while designing class hierarchy. Using inheritance you also gain code reuse. Code re-usability is definitely a good coding practice. Then what's the phrase "prefer composition over inheritance" and what's wrong with inheritance?
Actually there is nothing wrong with inheritance. Inheritance should be used to define hierarchical relationship. If you don't see hierarchical relationship between two entities, then don't use inheritance just to gain code re-usability. Your motive to use inheritance shouldn't be just code re-usability.
An example showing use of composition over inheritance
Let's consider a Television set. Television shows running pictures, produces sound and gets various channels. In real world Television make use of display screens to show pictures, speakers to produce sound and set of box to get channels. So Television should have all these functions. There are two options for the Television to exhibit above capabilities.
- OPTION #1: Television class can derive from Screen display, Speakers and set of box, etc to get their capability.
- OPTION #2: Instead compose Television class to get required functionality.
Disadvantage of using Inheritance to build Television class
Inheritance is a "IS A" relationship. In real world Television set IS not just a speaker. Saying Television IS A screen display doesn't make much sense. Television is much more than above said capabilities. So making Television class to derive from individual specialized classes doesn't establish a proper IS A relationship.
Advantage of preferring object composition over inheritance to build Television
Composition represents "HAS A" relationship. Applying this to television it makes sense to say, Television HAS A screen display, Television HAS A speaker and HAS A set of box. Here COMPOSITION represents the relationship better between the Television and the individual devices it makes use of. And hence the saying "PREFER COMPOSITION OVER INHERITANCE".
Having said "prefer composition over inheritance", inheritance isn't going away. Inheritance is definitely one of building block of OOPS, it has its use cases to represent real world hierarchical relationship; for more info refer Inheritance in OOPS
You might be interested in the below blog posts.