Inheritance vs Composition [duplicate]

百般思念 提交于 2019-12-05 05:04:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!