Can inheritance be replaced completely by composition?

后端 未结 4 1371
北海茫月
北海茫月 2020-12-28 23:22

This question is NOT question like \"inheritence vs composition\".

I understand completely how inheritance differs from composition, I know the Lisk

4条回答
  •  礼貌的吻别
    2020-12-28 23:43

    I think the real question here is inheritance vs. polymorphism. In popular languages like Java the two are combined, i.e. subtype polymorphism is only achieved through implementation inheritance. Go proves that polymorphism can be achieved without inheritance, even in a statically-typed language (and this was known before Go). So the question is, if you can have polymorphism without inheritance, why would you want it with inheritance?

    The modern answer seems to be... you wouldn't. Conflating inheritance with polymorphism assumes inheritance is the most common use case. Even James Gosling admits that implementation inheritance was a mistake. That isn't to say it's useless; but the use cases for inheritance could be covered by a framework or DSL rather than forced into every subtype relationship. In this regard, Go had the opportunity to learn from Java's mistake.

提交回复
热议问题