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