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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 铜鼓县| 沙坪坝区| 新河县| 富平县| 东宁县| 罗源县| 贡嘎县| 屯留县| 桓仁| 昌吉市| 察雅县| 进贤县| 依兰县| 华池县| 团风县| 丹东市| 博罗县| 隆德县| 和政县| 安国市| 贡山| 云林县| 南通市| 通州市| 吴旗县| 新巴尔虎右旗| 大关县| 泸溪县| 灵璧县| 靖边县| 仁化县| 萨嘎县| 舒城县| 广德县| 桦川县| 新闻| 华亭县| 衡南县| 建水县| 清镇市| 鄂州市|