Polymorphism ဆိုတာ object မတူပေမယ့် method name တူကို ခေါ်တဲ့အခါ ကိုယ်ပိုင်ပုံစံနဲ့ အလုပ်လုပ်နိုင်တာပါ။ Base class မှာ virtual ထားပြီး derived class မှာ override လုပ်နိုင်ပါတယ်။
csharp
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("The dog says: woof");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("The cat says: meow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.MakeSound();
myCat.MakeSound();
}
}ဘာကို သတိထားရမလဲ
Animal myDog = new Dog();ဆိုပြီး base type နဲ့ကိုင်ထားပေမယ့် တကယ် run တဲ့ method က Dog ထဲက override method ပါ။- ဒီ concept က plugin system, payment provider, notification channel လို pattern တွေမှာ အရမ်းအသုံးဝင်ပါတယ်။
You should see
The dog says: woof The cat says: meow