Member-only story
Effective Java! Favor Composition Over Inheritance
Today we get to take on one of the core items of object-oriented programming, inheritance. Particularly the dangers of inheritance and what is a better way in many cases. Inheritance is a core part of what makes object-oriented great and powerful when used correctly. What we will go over in this blog post is a particular pattern that gives us some of the capabilities of inheritance, while keeping us safe and maintaining encapsulation.
First off, there are a couple of different types of inheritance; the first is implementation inheritance which is one class extends the functionality of another class. This is the type of inheritance we will be talking about in this blog post. There is also interface inheritance where a class implements an interface or one interface extends another interface. This second type of inheritance is not covered in this blog post.
The core of what the title of this blog post comes down to is that inheritance breaks encapsulation. The problem comes in that changes to the super class can cause issues in the sub-classes without the sub-classes realizing it. This can lead to breakage, unexpected data leakage, and other issues that would best be avoided. This means the sub-classes need to evolve in lock step with their parent classes or risk encountering issues.
Let’s look at an example, and although contrived, the example in the book is solid at showing the issues. The idea behind this example class is that it creates a method for a user to have a…