OOP哲学(Scala编程中的组合和继承的摘录)

OOP philosophy (an extract on composition and inheritance from Programming in Scala)

在scala第239页的编程中,第一段说:

Composition and inheritance are two ways to define a new class in
terms of another existing class. If what you’re after is primarily
code reuse, you should in general prefer composition to inheritance.
Only inheritance suffers from the fragile base class problem, in which
you can inadvertently break subclasses by changing a superclass.

对我来说这还不清楚。有人能举一个这样的例子吗,最好是用一些代码?


脆弱的基类问题是所有支持继承的系统的通病。这意味着对父类型(继承自的类)所做的更改可能会产生意想不到的结果:更改会破坏对基类的假设。有关解释和示例,请参阅此相关的SO问题。

相比之下,scala将后向父类的添加导出到外部独立的特性,您可以使用mixin合成将其添加到子类型中。请参阅此示例,并将"EDOCX1"〔0〕视为您希望在定义基础AbsIterator后对其生效的更改。看看mixin如何不改变父级的任何内容,但在子类型中仍然可以很容易地重用?