看板 Soft_Job 關於我們 聯絡資訊
你這個例子來講 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
empireisme: 推喔 03/04 12:16
wulouise: measure的主詞不會是cup,表示非cup的責任 03/04 21:13
wulouise: 重點在責任歸屬,一大包通常是責任歸屬不明確的結果 03/04 21:14