Possible Duplicate:
Prefer composition over inheritance?
I wonder, why (or in which cases) should one consider inheritance instead of composition when there are so much cons of it:
- if we implement/override a method in a subclass which calls the method of the superclass, there's no guarantee that another version of our superclass (maybe some library) won't break our code
- if there will appear a new method in the superclass with the same signature that the sublclass method has, but with different return type, our class won't compile.
Therefore, I can't imagine, how on Earth we can rely on it. The superclass author may want to improve the performance and our client code may break down.
So my questions are:
- How are these problems solved (e.g. in standard Java libraries)?
- When to use inheritance and composition?