คลาสนามธรรมมีเมธอดนามธรรม ซึ่งจะถูกนำไปใช้งานโดยคลาสสืบทอด คลาสสืบทอดจะมีความสามารถเฉพาะเจาะจงมากขึ้น
ตัวอย่าง
using System;
namespace Demo {
abstract class Shape {
public abstract int area();
}
class Rectangle : Shape {
private int length;
private int width;
public Rectangle(int a = 0, int b = 0) {
length = a; width = b;
Console.WriteLine("Length of Rectangle: " + length);
Console.WriteLine("Width of Rectangle: " + 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();
}
}
}
ผลลัพธ์
Length of Rectangle: 14 Width of Rectangle: 8 Area: 112
คลาสนามธรรมของเราคือ:
abstract class Shape { public abstract int area(); }
กฎของคลาสนามธรรม
- ไม่สามารถสร้างอินสแตนซ์ของคลาสนามธรรมได้
- ไม่สามารถประกาศเมธอดนามธรรมนอกคลาสนามธรรมได้
- เมื่อคลาสประกาศ sealed ไม่สามารถสืบทอดได้ คลาสนามธรรมไม่สามารถเป็น sealed ได้