主頁(yè) > 知識(shí)庫(kù) > rudy 重載方法 詳解

rudy 重載方法 詳解

熱門標(biāo)簽:電話運(yùn)營(yíng)中心 硅谷的囚徒呼叫中心 Win7旗艦版 客戶服務(wù) 語(yǔ)音系統(tǒng) 百度AI接口 企業(yè)做大做強(qiáng) 呼叫中心市場(chǎng)需求
在子類里,我們可以通過(guò)重載父類方法來(lái)改變實(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 Student1Human
    |   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 Student2Human
    |   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í)會(huì)有兩種類型的人...

ruby> class DishonestHuman
    |   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 HonestHuman
    |   def train_toll(age)
    |     super(age) # pass the argument we were given
    |   end
    | end
   nil
ruby> Honest.new.train_toll(25)
Normal fare. 
   nil   

標(biāo)簽:海南 喀什 長(zhǎng)沙 山西 崇左 濟(jì)南 山西 安康

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《rudy 重載方法 詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266