C# KHÔNG hỗ trợ kế thừa đa dạng (multiple inheritance) cho class — một class chỉ có một base class trực tiếp. Để đạt hiệu ứng tương tự, dùng Interface.
Giải pháp: Interface
Một class có thể implement nhiều interface, mỗi interface định nghĩa một "hợp đồng" (contract) phương thức/thuộc tính.
Mã nguồn
using System;
namespace MyInheritance {
// Base class (duy nhất)
class Shape {
public void SetWidth(int w) => width = w;
public void SetHeight(int h) => height = h;
protected int width;
protected int height;
}
// Interface 1: Hành vi chi phí sơn
public interface IPaintCost {
int GetCost(int area);
}
// Interface 2: Hành vi vẽ (ví dụ thêm)
public interface IDrawable {
void Draw();
}
// Derived class: Kế thừa Shape + Implement 2 Interface
class Rectangle : Shape, IPaintCost, IDrawable {
public int GetArea() => width * height;
// Implement IPaintCost
public int GetCost(int area) => area * 80;
// Implement IDrawable
public void Draw() => Console.WriteLine($"Vẽ hình chữ nhật {width}x{height}");
}
class RectangleDemo {
static void Main(string[] args) {
Rectangle rect = new Rectangle();
rect.SetWidth(8);
rect.SetHeight(10);
int area = rect.GetArea();
Console.WriteLine("Diện tích: {0}", area);
Console.WriteLine("Chi phí sơn: ${0}", rect.GetCost(area));
rect.Draw();
Console.ReadKey();
}
}
}
Kết quả
Diện tích: 80
Chi phí sơn: $6400
Vẽ hình chữ nhật 8x10
Interface vs Abstract Class
| Đặc điểm | Interface | Abstract Class |
|---|---|---|
| Kế thừa đa dạng | ✓ (implement nhiều) | ✗ (chỉ 1 base class) |
| Implementation | Chỉ khai báo (trước C# 8), default implementation (C# 8+) | Có thể có code chung |
| Constructor | ✗ | ✓ |
| Fields | ✗ (chỉ static const) | ✓ |
| Access modifier | Mặc định public | Có thể private, protected... |
Default Interface Methods (C# 8.0+)
public interface ILogger {
void Log(string msg);
// Default implementation
void LogWarning(string msg) => Log($"WARN: {msg}");
void LogError(string msg) => Log($"ERROR: {msg}");
}
Lưu ý
- Interface định nghĩa "CÓ THỂ LÀM GÌ" (capability), không phải "LÀ GÌ" (identity).
- Composition over Inheritance: ưu tiên inject interface (Dependency Injection) thay vì kế thừa sâu.
- Diamond problem (vấn đề kim cương) không xảy ra với interface vì không có state chung.