国产探花免费观看_亚洲丰满少妇自慰呻吟_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 字符串處理

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 松溪县| 南岸区| 桃园县| 长宁县| 水富县| 宜黄县| 旬阳县| 南皮县| 卢氏县| 嵊州市| 大新县| 四平市| 高安市| 三门峡市| 务川| 娱乐| 越西县| 来宾市| 兴仁县| 高阳县| 丁青县| 南部县| 苏尼特左旗| 大丰市| 封丘县| 玉屏| 天气| 新民市| 恩施市| 衡东县| 大厂| 郑州市| 佳木斯市| 岑溪市| 肇源县| 金昌市| 高阳县| 五寨县| 锡林郭勒盟| 得荣县| 得荣县|