Polymorphism means that the sender of a stimulus does not need to know the receiving instance’s class. The receiving instance can belong to an arbitrary class.
If an instance sends a stimulus to another instance, but does not have to be aware of which class the receiving instance belongs to, we say that we have polymorphism.
翻成中文就是一個訊息(or event or stimulus) 的意義是由接收者(接收到的物件)來解釋,而不是由發訊者(sender)來解譯。只要接收者換成不同的物件或是 instance,系統的行為就會改變,具有這樣的特性就稱之為 polymorphism。
生活範例
金城武跟路人(準備接收訊息的兩個物件)在早餐店買早餐,金城武的早餐做好了,早餐店阿姨(sender) 於是喊了一聲 “帥哥~你的好了哦。” 理論上,阿姨期待只有金城武會上前取餐(接收者的行為),沒想到另一個路人也上前了。所以說,一個訊息的解釋是由接收者來決定而不是送出者。
實作面解譯
當子類別的物件宣告或轉型成父類別的型別時,還可以正確執行該子類別的行為。
public class Parent
{
public string Name { get; set; }
public virtual string PrintName()
{
return "Parent PrintName: " + this.Name;
}
}
public class Child : Parent
{
override public string PrintName()
{
return "Child PrintName: " + this.Name;
}
}
class Program
{
static void Main(string[] args)
{
Parent p = new Parent();
p.Name = "Parent Name";
TestPolymorphism(p);
Child c = new Child();
c.Name = "Child Name";
TestPolymorphism(c);
Console.Read();
}
static void TestPolymorphism(Parent parentObj)
{
// 雖然傳入的物件類別都是 Parent,但會依據實際的類別呼叫各自的方法
Console.WriteLine(parentObj.PrintName());
}
}