Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Abstraction ใน C# คืออะไร

Abstraction และ Encapsulation เกี่ยวข้องกัน Abstraction แสดงข้อมูลที่เกี่ยวข้อง Encapsulation ช่วย Implement ระดับ Abstraction ที่ต้องการ

ใน C# ทำได้ด้วย Abstract Class ให้ Implementation บางส่วน Derived Class จะ Implement ให้สมบูรณ์

จุดสำคัญ:

  • ไม่สามารถสร้าง Instance ของ Abstract Class ได้
  • ไม่สามารถประกาศ Abstract Method นอก Abstract Class ได้
  • Sealed Class ไม่สามารถ Inherit ได้ Abstract Class ไม่สามารถเป็น Sealed ได้

ตัวอย่าง

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; }
        public override int area() {
            Console.WriteLine("Rectangle class area :");
            return (width * length);
        }
    }
    class RectangleTester {
        static void Main(string[] args) {
            Rectangle r = new Rectangle(20, 15);
            double a = r.area();
            Console.WriteLine("Area: {0}", a);
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Rectangle class area :
Area: 300