介面Interface
Interface只定義Interface規格,方法成員內容則由繼承介面的衍生Class依需求提供實作,而介面最大好處是將方法成員的規格與實作分開。介面範例
以學校為例,學校會有加退選課系統,那讓我們就可以使用Interface來定相關加選課與退選課的規格,我們新增一個介面IElective.vb檔:Public Interface IElective '加選 Function enrollment(ByVal name As String, ByVal id As String) As Boolean '退選 Function withdrawal(ByVal name As String, ByVal id As String) As Boolean End Interface
介面實作
由於Interface必須由繼承的衍生Class實作所有方法,因此Interface一律為Public修飾詞,所以不需要修飾詞,而Interface命名習慣以大寫"I"為開頭。函式(Sub或Function)只需定義名稱及參數即可,實作的衍生Class必須實作所有方法成員,即使沒有實作相關內容,還是必須在實作的衍生Class裡保留定義Interface方法。Interface IElective → 由StudentClass.vb類別檔及AcademicAffairs.vb類別檔繼承,學生需要加退選課的功能,但學務處只需要學生加選課相關功能。此時AcademicAffairs.vb未實作退選課功能,但還是必須保留相關定義。實作Interface必須使用Implements關鍵字,當你輸入完Implements IElective後,Visual Studio會自動帶出所有Interface方法成員。注意方法的最後面會自加上Implements IElective.enrollment等關鍵字,代表此方法為實作Interface。
StudentClass.vb
Public Class StudentClass Implements IElective Public Function enrollment(ByVal name As String, ByVal id As String) As Boolean Implements IElective.enrollment '實作內容 End Function Public Function withdrawal(ByVal name As String, ByVal id As String) As Boolean Implements IElective.withdrawal '實作內容 End Function End Class
AcademicAffairs.vb
退選課功能未實作之功能,但必頁保留Interface定義。
Public Class AcademicAffairs Implements IElective Public Function enrollment(ByVal name As String, ByVal id As String) As Boolean Implements IElective.enrollment '實作 End Function Public Function withdrawal(ByVal name As String, ByVal id As String) As Boolean Implements IElective.withdrawal '未實作之功能,但必頁保留定義 End Function End Class
介面繼承
假設我們還有一個成績Interface:IStudentResults.vb介面檔,成績的計算必須依賴選課,所以Interface IElective被Interface IStudentResultsb繼承,Interface IStudentResults被Class AcademicAffairs繼承,而AcademicAffairs.vb類別檔必須實作所有Interface的方法成員(IElective及IStudentResults)。IStudentResults.vb:
Public Interface IStudentResults Inherits IElective Function Results(ByVal name As String, ByVal numeric As Double) As Double End Interface
AcademicAffairs.vb(須實作IStudentResults)。注意函數最後面會有Implements IElective.enrollment及Implements IStudentResults.Results等字,讓我們可以清楚看出來是實作那一個Interface的方法成員。
AcademicAffairs.vb
Public Class AcademicAffairs Implements IStudentResults Public Function enrollment(ByVal name As String, ByVal id As String) As Boolean Implements IElective.enrollment '實作 End Function Public Function withdrawal(ByVal name As String, ByVal id As String) As Boolean Implements IElective.withdrawal '實作 End Function Public Function Results(ByVal name As String, ByVal numeric As Double) As Double Implements IStudentResults.Results '實作 End Function End Class
多重介面
在.Net Framework不充許多重Class繼承,但卻可以多重Interface繼承來同時實作多個介面。實作多重Interface繼承只在逐一加入Implements InterfaceName即可。Public Class OOP Implements IAnimals Implements IBehavior '實作IAnimals及IBehavior所有方法成員 End Class
沒有留言:
張貼留言
感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。