Kế thừa cho phép định nghĩa class dựa trên class khác (base class -> derived class).
Cú pháp
class Derived : Base { ... }
Ví dụ: Shape -> Rectangle
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 Demo
{
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
rect.SetWidth(5);
rect.SetHeight(7);
Console.WriteLine("Diện tích: {0}", rect.GetArea());
Console.ReadKey();
}
}
}
Kết quả
Diện tích: 35
Đặc điểm kế thừa C#:
- Single inheritance (chỉ 1 base class)
- Đa interface:
class A : Base, I1, I2 protected: truy cập trong derived classvirtual/override: đa hìnhsealed: ngăn kế thừa- Constructor base gọi tự động (hoặc
base())