Re: [請益] 多型用在哪

看板Soft_Job作者 (雲川閒步)時間3年前 (2021/03/04 12:13), 編輯推噓1(102)
留言3則, 2人參與, 3年前最新討論串2/5 (看更多)
你這個例子來講 measure()的引數就是Cup型別 所以宣告變數c的型別必須是Cup 至於為什麼measure()不放在Cup裡面 是因為如果所有Cup的使用者都把他們要的method 放在Cup裡面 很快Cup就會變一大包,造成維護困難 ※ 引述《empireisme (empireisme)》之銘言: : 如題 : 看了stackoverflow的一個例子 : class Cup { : int capacity : } : class TeaCup : Cup { : string flavour : } : class CoffeeCup : Cup { : string brand : } : Cup c = new CoffeeCup(); : public int measure(Cup c) { : return c.capacity : } : 他的解釋是 : you can pass just a Cup instead of a specific instance. This aids in : generality because you don't have to provide a specific measure() instance : per each cup type : 問題是我不是只要 : 在Cup 類別中定義 measure這個方法 不就可以了嗎 : 為何不要在宣告物件的時候都 : 使用 : CoffeeCup c= new CoffeeCup(); : 請問多型的用途是? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 72.70.46.113 (美國) ※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1614831195.A.6C4.html

03/04 12:16, 3年前 , 1F
推喔
03/04 12:16, 1F

03/04 21:13, 3年前 , 2F
measure的主詞不會是cup,表示非cup的責任
03/04 21:13, 2F

03/04 21:14, 3年前 , 3F
重點在責任歸屬,一大包通常是責任歸屬不明確的結果
03/04 21:14, 3F
文章代碼(AID): #1WG5vRR4 (Soft_Job)
文章代碼(AID): #1WG5vRR4 (Soft_Job)