• 继承

    继承

    Inheritance

    继承

    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.

    我们知道,所有的(Cat)都是哺乳动物(Mammal),而所有的哺乳动物都是动物。较小的类继承了它们所属的较大类的特征。如果所有的哺乳动物都呼吸,那么所有的也都需要呼吸。

    We can express this concept in ruby:

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

    1. ruby> class Mammal
    2. | def breathe
    3. | puts "inhale and exhale"
    4. | end
    5. | end
    6. nil
    7. ruby> class Cat<Mammal
    8. | def speak
    9. | puts "Meow"
    10. | end
    11. | end
    12. nil

    Though we didn’t specify how a Cat 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 speak method, our cats can both breathe and speak.

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

    1. ruby> tama = Cat.new
    2. #<Cat:0xbd80e8>
    3. ruby> tama.breathe
    4. inhale and exhale
    5. nil
    6. ruby> tama.speak
    7. Meow
    8. nil

    There will be situations where certain properties of the superclass should not be inherited by a particular subclass. Though birds generally know how to fly, penguins are a flightless subclass of birds.

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

    1. ruby> class Bird
    2. | def preen
    3. | puts "I am cleaning my feathers."
    4. | end
    5. | def fly
    6. | puts "I am flying."
    7. | end
    8. | end
    9. nil
    10. ruby> class Penguin<Bird
    11. | def fly
    12. | fail "Sorry. I'd rather swim."
    13. | end
    14. | end
    15. nil

    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.

    这种继承的使用有时被称为微分编程,这是面向对象编程的好处之一。

    上一章 类
    下一章 重新定义方法