• 重新定义方法

    重新定义方法

    Redefinition of methods

    重新定义方法

    In a subclass, we can change the behavior of the instances by redefining superclass methods.

    子类中,我们可以通过重定义继承自父类的方法来改变实例的行为。

    1. ruby> class Human
    2. | def identify
    3. | puts "I'm a person."
    4. | end
    5. | def train_toll(age)
    6. | if age < 12
    7. | puts "Reduced fare.";
    8. | else
    9. | puts "Normal fare.";
    10. | end
    11. | end
    12. | end
    13. nil
    14. ruby> Human.new.identify
    15. I'm a person.
    16. nil
    17. ruby> class Student1<Human
    18. | def identify
    19. | puts "I'm a student."
    20. | end
    21. | end
    22. nil
    23. ruby> Student1.new.identify
    24. I'm a student.
    25. nil

    Suppose we would rather enhance the superclass’s identify method than entirely replace it. For this we can use super.

    假如我们想要增强父类的的identify方法,而不是完全替换它。为此我们可以使用super

    1. ruby> class Student2<Human
    2. | def identify
    3. | super
    4. | puts "I'm a student too."
    5. | end
    6. | end
    7. nil
    8. ruby> Student2.new.identify
    9. I'm a person.
    10. I'm a student too.
    11. nil

    super lets us pass arguments to the original method. It is sometimes said that there are two kinds of people…

    super让我们将传递参数给原始的方法。有时会说,有两种人…

    1. ruby> class Dishonest<Human
    2. | def train_toll(age)
    3. | super(11) # 我们想要便宜的车票
    4. | end
    5. | end
    6. nil
    7. ruby> Dishonest.new.train_toll(25)
    8. Reduced fare.
    9. nil
    10. ruby> class Honest<Human
    11. | def train_toll(age)
    12. | super(age) # 传递我们给的参数
    13. | end
    14. | end
    15. nil
    16. ruby> Honest.new.train_toll(25)
    17. Normal fare.
    18. nil

    上一章 继承
    下一章 访问控制