Abstract class chứa abstract method, được implement bởi derived class. Derived class có chức năng chuyên biệt hơn.
Ví dụ
using System;
namespace Demo {
abstract class Shape { public abstract int area(); }
class Rectangle : Shape {
private int length, width;
public Rectangle(int a = 0, int b = 0) { length = a; width = b; Console.WriteLine("Length: " + length); Console.WriteLine("Width: " + width); }
public override int area() { return (width * length); }
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(14, 8);
double a = r.area();
Console.WriteLine("Area: {0}", a); Console.ReadKey();
}
}
}
Kết quả
Length of Rectangle: 14 Width of Rectangle: 8 Area: 112
Quy tắc abstract class:
- Không thể tạo instance của abstract class
- Không thể khai báo abstract method ngoài abstract class
- Abstract class không thể declared sealed