问题
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?
回答1:
Your first objection also applies to composition: if the implementation of a method that you call changes, there's no guarantee that your code won't break.
The second objection is actually a good thing, since you'll immediately notice there is a problem with the new version of the API.
The problem doesn't have much to do with inheritance/composition. If the public contract of a class changes from version to version, you'll have to make changes in your code to accomodate these changes. The problem is solved by avoiding changes that would be backward-incompatible. Providing a new API can be the solution (See io, followed by nio, followed by nio2, for example). Otherwise, release notes and migration documentation are there to help transitioning from one version of an API to another.
Inheritance is used when there is a is-a relationship between your class and the other class. Composition is used when there is a has-a relationship between your class and the other class.
来源:https://stackoverflow.com/questions/11031843/inheritance-vs-composition