Method Overriding (การลบล้าง/เขียนทับ)
- ใช้
virtual ใน Base Class และ override ใน Derived Class
- Polymorphism ทำงาน - เรียกเมธอดตาม Object จริง (Runtime)
- ใช้กับ Abstract Method ได้
ตัวอย่าง Overriding
using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int Area();
}
class Rectangle : Shape
{
private int length, width;
public Rectangle(int a = 0, int b = 0)
{
length = a; width = b;
}
public override int Area()
{
Console.WriteLine("Rectangle class area:");
return width * length;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.Area();
Console.WriteLine("Area: {0}", a);
Console.ReadKey();
}
}
}
Method Hiding / Shadowing (การซ่อน)
- ใช้
new Keyword ใน Derived Class
- ไม่ใช่ Polymorphism - เรียกตาม Type ของ Variable (Compile-time)
- Base Class ไม่ต้องมี virtual
ตัวอย่าง Hiding
using System;
class Demo
{
public class Parent
{
public string Display() => "Parent Class!";
}
public class Child : Parent
{
public new string Display() => "Child Class!";
}
static void Main()
{
Child child = new Child();
Console.WriteLine(child.Display()); // "Child Class!"
Parent parent = child; // Upcast
Console.WriteLine(parent.Display()); // "Parent Class!" - เรียก Parent version
}
}
ตารางเปรียบเทียบ
| ลักษณะ | Overriding | Hiding (new) |
| Keyword | virtual / override | new |
| Polymorphism | ใช่ (Runtime) | ไม่ (Compile-time) |
| Base ต้อง virtual | ใช่ | ไม่ |
| เข้าถึง Base | base.Method() | ((Base)derived).Method() |