在子类里,我们可以通过重载父类方法来改变实体的行为.
ruby>classHuman
|defidentify
|print"I'maperson.\n"
|end
|deftrain_toll(age)
|ifage<12
|print"Reducedfare.\n";
|else
|print"Normalfare.\n";
|end
|end
|end
nil
ruby>Human.new.identify
I'maperson.
nil
ruby>classStudent1
|defidentify
|print"I'mastudent.\n"
|end
|end
nil
ruby>Student1.new.identify
I'mastudent.
nil
如果我们只是想增强父类的identify方法而不是完全地替代它,就可以用super.
ruby>classStudent2
|defidentify
|super
|print"I'mastudenttoo.\n"
|end
|end
nil
ruby>Student2.new.identify
I'mahuman.
I'mastudenttoo.
nil
super也可以让我们向原有的方法传递参数.这里有时会有两种类型的人...
ruby>classDishonest
|deftrain_toll(age)
|super(11)#wewantacheapfare.
|end
|end
nil
ruby>Dishonest.new.train_toll(25)
Reducedfare.
nil
ruby>classHonest
|deftrain_toll(age)
|super(age)#passtheargumentweweregiven
|end
|end
nil
ruby>Honest.new.train_toll(25)
Normalfare.
nil