ruby> class Human | def identify | print "I'm a person.\n" | end | def train_toll(age) | if age < 12 | print "Reduced fare.\n"; | else | print "Normal fare.\n"; | end | end | end nil ruby> Human.new.identify I'm a person. nil ruby> class Student1<Human | def identify | print "I'm a student.\n" | end | end nil ruby> Student1.new.identify I'm a student. nil
如果我们只是想增强父类的 identify 方法而不是完全地替代它,就可以用 super.
ruby> class Human | def identify | print "I'm a person.\n" | end | def train_toll(age) | if age < 12 | print "Reduced fare.\n"; | else | print "Normal fare.\n"; | end | end | end nil ruby> Human.new.identify I'm a person. nil ruby> class Student1<Human | def identify | print "I'm a student.\n" | end | end nil ruby> Student1.new.identify I'm a student. nil
super 也可以让我们向原有的方法传递参数.这里有时会有两种类型的人...
ruby> class Human | def identify | print "I'm a person.\n" | end | def train_toll(age) | if age < 12 | print "Reduced fare.\n"; | else | print "Normal fare.\n"; | end | end | end nil ruby> Human.new.identify I'm a person. nil ruby> class Student1<Human | def identify | print "I'm a student.\n" | end | end nil ruby> Student1.new.identify I'm a student. nil