Re: [請益] 多型用在哪

作者: cateran (雲川閒步)   2021-03-04 12:13:13
你這個例子來講
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();
: 請問多型的用途是?
作者: empireisme (empireisme)   2021-03-04 12:16:00
推喔
作者: wulouise (在線上!=在電腦前)   2021-03-04 21:13:00
measure的主詞不會是cup,表示非cup的責任重點在責任歸屬,一大包通常是責任歸屬不明確的結果

Links booklink

Contact Us: admin [ a t ] ucptt.com