Inheritance (การสืบทอด) ใน C#
Inheritance ช่วยให้สร้าง Class ใหม่ (Derived/Child) จาก Class เดิม (Base/Parent) ได้ โดยสืบทอด Fields, Methods, Properties มาใช้งาน/ขยาย/แก้ไข (Override) ได้
คุณสมบัติหลัก
- Single Inheritance: Class เดียวสืบทอดจาก Base Class เดียว (แต่ Implement Interface ได้หลายตัว)
- Access Modifiers:
public,protected,internal,protected internal,private protected - Virtual/Override: Polymorphism (Late Binding)
- Abstract/Sealed: บังคับ Overload / ห้ามสืบทอด
- base Keyword: เรียก Base Constructor/Method
ตัวอย่าง: Base และ Derived Class
using System;
namespace InheritanceApplication
{
// Base Class
class Shape
{
protected int Width, Height; // Derived Class เข้าถึงได้
public void SetWidth(int w) => Width = w;
public void SetHeight(int h) => Height = h;
}
// Derived Class
class Rectangle : Shape
{
public int GetArea() => Width * Height;
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
rect.SetWidth(5);
rect.SetHeight(7);
Console.WriteLine($"Total area: {rect.GetArea()}"); // 35
Console.ReadKey();
}
}
}
ผลลัพธ์
Total area: 35
Access Modifiers ใน Inheritance
| Modifier | Base Class | Derived Class | Outside Assembly |
|---|---|---|---|
public | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✗ |
internal | ✓ | ✓ (Same Assembly) | ✗ |
protected internal | ✓ | ✓ | ✓ (Derived in Other Assembly) |
private protected | ✓ | ✓ (Same Assembly Only) | ✗ |
private | ✓ | ✗ | ✗ |
การเรียก Base Constructor
class Animal
{
public string Name;
public Animal(string name) { Name = name; Console.WriteLine($"Animal: {name}"); }
}
class Dog : Animal
{
public Dog(string name) : base(name) { Console.WriteLine($"Dog: {name}"); }
}
// new Dog("Buddy");
// Output:
// Animal: Buddy
// Dog: Buddy
Composition over Inheritance
แนะนำให้ใช้ Composition (Has-A) มากกว่า Inheritance (Is-A) เพื่อ Loose Coupling และ Flexibility