在子類里,我們可以通過重載父類方法來改變實體的行為.
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?Student2<Human
????|???def?identify
????|?????super
????|?????print?"I'm?a?student?too.\n"
????|???end
????|?end
???nil
ruby>?Student2.new.identify
I'm?a?human.
I'm?a?student?too.
???nil?
super?也可以讓我們向原有的方法傳遞參數(shù).這里有時會有兩種類型的人...
ruby>?class?Dishonest<Human
????|???def?train_toll(age)
????|?????super(11)?#?we?want?a?cheap?fare.
????|???end
????|?end
???nil
ruby>?Dishonest.new.train_toll(25)
Reduced?fare.?
???nil
ruby>?class?Honest<Human
????|???def?train_toll(age)
????|?????super(age)?#?pass?the?argument?we?were?given
????|???end
????|?end
???nil
ruby>?Honest.new.train_toll(25)
Normal?fare.?
???nil?
版權(quán)聲明:RUBY文檔中心的所有文章標(biāo)明[原創(chuàng)]的均為本站作品,版權(quán)屬RUBY中文化計劃,若轉(zhuǎn)載請注明;標(biāo)明[翻譯]的其外文版權(quán)歸原作者,譯文版權(quán)屬RUBY中文化計劃;標(biāo)明[轉(zhuǎn)貼]的,若原作者感到侵犯了他的著作權(quán),那么請及時跟主持人聯(lián)系,我們會盡快更正。
?