Runtime Polymorphism (Dynamic Polymorphism / Late Binding) - เมธอดที่เรียกใช้ถูกตัดสินใจที่ **Runtime** ตาม Object Type จริง
กลไก 2 แบบ
- Abstract Classes - Abstract Methods บังคับ Override
- Virtual Functions - Virtual Methods สามารถ Override ได้
1. Abstract Classes
using System;
namespace PolymorphismApplication
{
// Abstract Class - ไม่สามารถ Instantiate เองได้
abstract class Shape
{
public abstract int Area(); // Abstract Method - ไม่มี Body
}
class Rectangle : Shape
{
private int length, width;
public Rectangle(int a = 0, int b = 0)
{
length = a; width = b;
}
// ต้อง Override
public override int Area()
{
Console.WriteLine("Rectangle class area:");
return width * length;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Shape shape = new Rectangle(10, 7); // Upcast
double area = shape.Area(); // Runtime: เรียก Rectangle.Area()
Console.WriteLine("Area: {0}", area);
Console.ReadKey();
}
}
}
ผลลัพธ์
Rectangle class area: Area: 70
2. Virtual Functions
using System;
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Some sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
class Program
{
static void Main()
{
Animal[] animals = { new Dog(), new Cat(), new Animal() };
foreach (var a in animals)
{
a.MakeSound(); // Runtime Polymorphism
}
}
}
ผลลัพธ์
Woof! Meow! Some sound
สรุป: Abstract vs Virtual
| คุณสมบัติ | Abstract Method | Virtual Method |
|---|---|---|
| Body ใน Base | ไม่มี (ต้อง Override) | มี (Default Implementation) |
| Override | บังคับ | เลือกได้ |
| Class | ต้องเป็น Abstract Class | Class ธรรมดาได้ |
| Sealed Override | ได้ (sealed override) | ได้ (sealed override) |