Reputation: 542
The design principle says that favor composition over inheritance. But I would like to know if there is a case where we can use only inheritance and not composition.
Essentially I am looking at a case where strategy pattern fails over inheritance.
Upvotes: 1
Views: 108
Reputation: 15990
In my opinion you can emulate all of the behavior of inheritance via composition.
That being said, inheritance can, in some cases, be helpful to guarantee type safety or the existence of a reasonable fallback.
An example where you are forced to use inheritance is when you must interact with an external lib that expects a certain type to be passed, so, if you want to extend that type's behavior, you have no choice but to extend it.
If you control the overall design of your application, then favor using interfaces to guarantee type safety and method signatures, and composition to create behavior.
Also, if you haven't already, and are the least bit serious about programming in Java, I would recommend that you read Effective Java 2nd Edition.
It's probably the best book on Java patterns and good practices there is, and no matter you skill level today, if you haven't read it, you'll learn some useful things.
Upvotes: 4