composition vs inheritance : Java Glossary
- composition vs inheritance
Let’s say you wanted to augment the ArrayList
class. There are two ways you could do it:
- Via inheritance. Your new class extends ArrayList.
- Via composition. Your new class includes a reference to an ArrayList Object.
Advantages Of Inheritance
- If all you want to do is modify one or two methods, you just have to override
those methods. All the other methods of ArrayList continue to work
automatically as methods of your class.
- The base ArrayList class will use any methods you
override. They may work now, but if the implementation of ArrayList changes, they may stop working.
Advantages Of Composition
- Pros like Joshua Bloch generally recommend composition.
- If ArrayList acquired some new methods, they would
not automatically be exposed to the clients of your class. If you wanted them
exposed, you would have to write wrappers.
- Your code and the base code of ArrayList are kept in two airtight boxes. There
is less chance of unexpected interactions.
- You have to write dozens of mindless wrapper methods around every method of
the base ArrayList class that you want to expose to the
clients of your class.
wrapper is a tiny method that just calls the corresponding method of the same name on the ArrayList Object.
Rules of Thumb
- Unless you have very good reason to use inheritance, use composition.
- Only use inheritance when you write both the base and extended class.