rudy 重載方法 詳解
更新時間:2007年11月24日 14:11:10 作者:
在子類里,我們可以通過重載父類方法來改變實體的行為.
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
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
相關文章
實例解析Ruby設計模式編程中Strategy策略模式的使用
這篇文章主要介紹了Ruby設計模式編程中Strategy策略模式的使用實例,Strategy模式在Ruby on Rails框架開發(fā)中也經(jīng)常用到,需要的朋友可以參考下2016-03-03Windows下安裝配置Ruby的debug工具ruby-debug-base19
這篇文章主要介紹了Windows下安裝配置Ruby的debug工具ruby-debug-base19的方法,同時講解了Ruby的IDE RubyMine中的相關配置方法,需要的朋友可以參考下2016-03-03