Base Class คือคลาสที่มีอยู่แล้ว ให้ Derived Class (คลาสลูก) สืบทอด Members (Data/Methods) ไปใช้ แทนที่จะเขียนใหม่ทั้งหมด
คลาสหนึ่งสามารถสืบทอดจากหลาย Base Classes หรือ Interfaces ได้
Syntax
<access-specifier> class <base_class> { ... }
class <derived_class> : <base_class> { ... }
ตัวอย่าง
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w) { width = w; }
public void setHeight(int h) { height = h; }
protected int width;
protected int height;
}
// Derived Class
class Rectangle : Shape
{
public int getArea() { return (width * height); }
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}