Kế thừa đơn (Single Inheritance): Một lớp dẫn xuất (derived/child) kế thừa từ một lớp cơ sở (base/parent). C# chỉ hỗ trợ đơn kế thừa cho class.
Mã nguồn
using System;
namespace MyApplication {
class Demo {
static void Main(string[] args) {
// Lớp cơ sở
Father f = new Father();
f.Display(); // Output: Display
// Lớp dẫn xuất
Son s = new Son();
s.Display(); // Kế thừa từ Father
s.DisplayOne(); // Mới của Son
Console.ReadKey();
}
}
// Base class
class Father {
public void Display() {
Console.WriteLine("Display");
}
}
// Derived class
class Son : Father {
public void DisplayOne() {
Console.WriteLine("DisplayOne");
}
}
}
Kết quả
Display
Display
DisplayOne
Sơ đồ kế thừa
Father (Base) │ ▼ Son (Derived) — có Display() + DisplayOne()
Truy cập thành viên
| Modifier | Truy cập từ Derived | Truy cập từ bên ngoài |
|---|---|---|
public | ✓ | ✓ |
protected | ✓ | ✗ |
private | ✗ | ✗ |
internal | ✓ (cùng assembly) | ✓ (cùng assembly) |
protected internal | ✓ | ✓ (cùng assembly) |
private protected | ✓ (cùng assembly) | ✗ |
Constructor trong kế thừa
class Father {
public Father(string name) { Name = name; }
public string Name { get; }
}
class Son : Father {
// BẮT BUỌC gọi base constructor
public Son(string name, int age) : base(name) {
Age = age;
}
public int Age { get; }
}
Lưu ý
- C# không hỗ trợ multiple inheritance cho class — dùng Interface để đạt hiệu ứng tương tự.
- Mọi class đều ngầm kế thừa từ
object(root type). basetừ khóa truy cập thành viên lớp cơ sở (constructor, method, property).