继承

    继承

    Our classification of objects in everyday life is naturally hierarchical.

    我们在日常生活中对物品的分类是自然分层的。

    We know that all cats are mammals, and all mammals are animals. Smaller classes inherit characteristics from the larger classes to which they belong. If all mammals breathe, then all cats breathe.

    We can express this concept in ruby:

    我们可以用Ruby来表达这个概念:

    Though we didn’t specify how a should breathe, every cat will inherit that behavior from the Mammal class since Cat was defined as a subclass of Mammal. (In OO terminology, the smaller class is a subclass and the larger class is a superclass.) Hence from a programmer’s standpoint, cats get the ability to breathe for free; after we add a method, our cats can both breathe and speak.

    尽管我们没有具体说明一只Cat应该如何呼吸,但每只Cat都会继承Mammal的行为,因为被定义为Mammal的一个子类。(在OO的术语中,较小的类是子类,较大的类是父类。)因此,从程序员的角度来看,猫咪可以自由地呼吸。在我们添加了方法之后,我们的猫既可以呼吸也可以叫了。

    在某些情况下,父类的某些属性不应该由特定的子类继承。尽管鸟类一般都知道如何飞行,但是企鹅是鸟类的一个不能飞行的子类。

    Rather than exhaustively define every characteristic of every new class, we need only to append or to redefine the differences between each subclass and its superclass.

    相比详尽地定义每一个新类的每一个特征,我们仅仅需要添加或者重定义每个和它的父类之间的差异。

    This use of inheritance is sometimes called differential programming. It is one of the benefits of object-oriented programming.


    下一章 重新定义方法