本鲁 OO 不太好
但你这例子多型吗
这就只是子类别继承父类别的属性吧
多型比较像这样吧
class DataLoader {
protected virtual string GetData() {
//..
}
public string Process() {
// ...
string data = GetData();
// ...
}
}
class NetworkLoader: DataLoader {
protected override string GetData() {
// get from network...
}
}
class FileLoader: DataLoader {
protected override string GetData() {
// get from file...
}
}
DataLoader loader = networkEnabled ? new NetowrkLoader() : new FileLoader();
string processedData = loader.Process();
让子类别作他擅长的部份
父类别程式码部分重用并且隐藏子类别的实作细节
函数只要能够接受父类别的实体
所以使用父类别的函数也可以重用
要扩充只需要继承父类别并且实作部分方法
※ 引述《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();
: 请问多型的用途是?