คลาสนามธรรมประกอบด้วยเมธอดนามธรรมซึ่งใช้งานโดยคลาสที่ได้รับ คลาสที่ได้รับมีฟังก์ชันพิเศษมากกว่า
ต่อไปนี้เป็นตัวอย่างการแสดงการใช้คลาสนามธรรมใน C#
ตัวอย่าง
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();
} ต่อไปนี้เป็นกฎเกี่ยวกับคลาสนามธรรม
- คุณไม่สามารถสร้างอินสแตนซ์ของคลาสนามธรรมได้
- คุณไม่สามารถประกาศวิธีการที่เป็นนามธรรมนอกคลาสนามธรรมได้
- เมื่อคลาสถูกประกาศปิดผนึก คลาสนั้นไม่สามารถสืบทอด คลาสนามธรรมไม่สามารถประกาศปิดผนึก