Interface
Interface là hợp đồng ngữ pháp (syntactical contract) mà các class kế thừa phải tuân theo. Interface định nghĩa phần "gì" (what), class triển khai định nghĩa phần "như thế nào" (how).
Ví dụ Interface
public interface ITransactions
{
void ShowTransaction();
double GetAmount();
}
public class Transaction : ITransactions
{
private string tCode, date;
private double amount;
public Transaction(string c, string d, double a)
{ tCode = c; date = d; amount = a; }
public double GetAmount() => amount;
public void ShowTransaction()
{
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", GetAmount());
}
}
Inheritance (Kế thừa)
Kế thừa cho phép định nghĩa class dựa trên class khác, dễ dàng tạo/maintain ứng dụng, tái sử dụng code, tăng tốc độ triển khai.
Mối quan hệ IS-A: Mammal IS-A Animal, Dog IS-A Mammal → Dog IS-A Animal.
Ví dụ Inheritance
using System;
namespace InheritanceApplication
{
class Shape
{
protected int width;
protected int height;
public void SetWidth(int w) { width = w; }
public void SetHeight(int h) { height = h; }
}
// 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()); // 35
Console.ReadKey();
}
}
}
Kết quả
Total area: 35
Lưu ý: C# chỉ hỗ trợ đơn kế thừa (single inheritance) cho class, nhưng implement nhiều interface. Dùng virtual/override cho polymorphism, sealed để cấm kế thừa/override.