国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

rudy 重載方法 詳解

2019-10-26 19:19:07
字體:
來源:轉載
供稿:網友
在子類里,我們可以通過重載父類方法來改變實體的行為.

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 也可以讓我們向原有的方法傳遞參數.這里有時會有兩種類型的人...

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
上一篇:rudy 繼承 概念

下一篇:Ruby 字符串處理

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 罗田县| 栾城县| 阳朔县| 东明县| 永登县| 涟源市| 锦州市| 云南省| 临桂县| 武穴市| 封丘县| 措美县| 太仓市| 东港市| 陆良县| 金湖县| 闻喜县| 尼玛县| 永春县| 西和县| 仁布县| 鲁山县| 桐庐县| 云浮市| 淳化县| 望谟县| 探索| 德庆县| 嘉鱼县| 大田县| 靖安县| 琼结县| 佳木斯市| 象州县| 宽甸| 巍山| 象州县| 施甸县| 习水县| 永靖县| 永平县|