问题描述
继承有哪些替代方法?
推荐答案
有效的Java:支持组合而不是继承。 (这实际上来自Gang of Four,也是如此)。
Effective Java: Favor composition over inheritance. (This actually comes from Gang of Four, as well).
他所做的案例是,如果扩展类不是,那么继承会导致很多不合时宜的副作用明确设计为继承。例如,对 super.someMethod()
的任何调用都会引导您通过未知代码的意外路径。
The case he makes is that inheritance can cause a lot of unseemly side effects, if the extended class was not explicitly designed to be inherited. For example, any calls to super.someMethod()
can lead you through unexpected paths of unknown code.
,保留对本来会扩展的类的引用,并委托给它。
Instead, hold a reference to the class you would have otherwise extended, and delegate to it.
这是一个指向与Erich Gamma,他谈到了这个概念。
Here is a link to an interview with Erich Gamma where he talks about the concept a bit.
这篇关于java:继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!