Hello guys, Favor composition over inheritance is one of the popular object-oriented design principles, which helps to create flexible and maintainable code in Java and other object-oriented languages.
Many times I have seen people suggesting use composition instead of inheritance, in fact, my favorite books like Head First Design Patterns also advocate this design principle.
In fact, that’s where I first come to know about this concept.
The Head First books have their own way of explaining, why composition is better than inheritance, and though it's long it's quite interesting and informative.
It was also the first chapter of this book, which helped me a lot in understanding this key OOP concept. If you haven’t read Head First Design Patterns, yet, I would definitely recommend you to read it.
In this Java and OOP tutorial, I have tried to summarize my experience around composition and inheritance in two main categories, first, the difference between composition and inheritance, and second, when to use Composition over inheritance in Java.
I have already mentioned this design principle, in my list of 10 OOP and SOLID design principles for Java programmers, here we will take a closer look.
Just to revise, composition and Inheritance are ways to reuse code to get additional functionality. In Inheritance, a new class, which wants to reuse code, inherits an existing class, known as a superclass. This new class is then known as the subclass.
Btw, In order to best understand design patterns, you need to work out some scenarios, examples, etc.
It's best to get this kind of knowledge as part of your work but even if you don't get there, you can supplement them by joining these online Java design pattern courses like Design Patterns in Java on Udemy and doing some object-oriented software design exercises like How to design an efficient Parking lot and the ones given in Codemia.io
5 Reasons to Prefer Composition Over Inheritance in Java
On Composition, a class, which desires to use the functionality of an existing class, doesn't inherit, instead it holds a reference of that class in a member variable, that’s why the name composition.
Inheritance and composition relationships are also referred as IS-A and HAS-A relationships in Java.
Keep reading with a 7-day free trial
Subscribe to Javarevisited Newsletter to keep reading this post and get 7 days of free access to the full post archives.