|
|
|
Interface
Interface คือ การกำหนดความสามารถของ object ใน OOP ซึ่ง class ใด implement interface ก็เป็นการสัญญาว่าจะมีความสามารถตามที่ interface กำหนดไว้ พูดง่ายๆก็คือ เป็นการแยก specification ออกจาก ส่วน implementation ของ class นั่นเอง ดังนั้นการติดต่อกับ object ที่สร้างขึ้นจาก class ดังกล่าวต้องผ่าน interface เท่านั้น
C# สนับสนุนการทำงานแบบ inerface โดยใช้ keyword interface
using System; |
interface นั้นเป็น abstract data type ซึ่งไม่สามารถ instantiate ได้ การใช้งานจะต้องสร้าง object ก่อน (เช่น Math) แล้ว ให้ reference ของ interface ชี้ไปยัง object นั้น
class หลายๆ class สามารถ implement interface เดียวกันได้ โดยแต่ละ class ก็มีส่วน implementation แตกต่างกันไป ซึ่งการเรียก method ของ interface จะขึ้นอยู่กับ ชนิดของ object ที่ interface ผูกติดอยู่ หมายความว่า interface สามารถทำ polymorphism ได้ เช่น เดียวกับกลไกของ virtual function ของ class ธรรมดานั่นเอง
|
method ที่ทำ polymorphism ต้องเป็น method ที่เป็น virtual , abstract หรือเป็น method ของ interface เท่านั้น
Multiple Inheritance with Interface
Interface ต่างจาก abstract class อย่างไร ?
คำตอบก็คือชื่อหัวข้อครับ C# ไม่อนุญาติให้ทำ multiple inheritance กับclass แต่ interface ทำได้ครับ
11/10/44