最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

rudy 重載方法 詳解

 更新時(shí)間:2007年11月24日 14:11:10   作者:  
在子類里,我們可以通過重載父類方法來改變實(shí)體的行為.

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  


如果我們只是想增強(qiáng)父類的 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ù).這里有時(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   

相關(guān)文章

最新評論

大名县| 张家川| 漳平市| 黄龙县| 从化市| 桐乡市| 蒙城县| 五河县| 乌鲁木齐市| 来宾市| 林口县| 沈阳市| 房产| 杭州市| 奉化市| 河曲县| 板桥市| 富川| 抚顺县| 海原县| 什邡市| 尉犁县| 临澧县| 巴塘县| 长兴县| 苗栗市| 始兴县| 南通市| 阿克苏市| 贺州市| 永川市| 北流市| 湘阴县| 城市| 潼南县| 饶阳县| 蓝山县| 武陟县| 呼玛县| 新丰县| 华亭县|