在子類里,我們可以通過重載父類方法來改變實體的行為.
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