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

首頁 > 編程 > Ruby > 正文

rudy 重載方法 詳解

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

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
ruby> Honest.new.train_toll(25)
Normal fare. 
   nil   

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 澄江县| 南雄市| 商洛市| 巨野县| 新建县| 潮州市| 汕头市| 甘谷县| 锡林浩特市| 芦溪县| 建宁县| 淮南市| 额敏县| 梁平县| 通州市| 麻栗坡县| 康马县| 临沭县| 集安市| 石门县| 滦平县| 辉县市| 黄陵县| 乐陵市| 洛南县| 通渭县| 伊宁市| 普宁市| 泗阳县| 教育| 文安县| 河北区| 永福县| 莒南县| 朝阳区| 仙居县| 拉萨市| 北碚区| 澄迈县| 开原市| 漳州市|