HOW TO:建立衍生類別
更新:2007 年 11 月
Inherits 陳述式會導致類別繼承指定類別中所有的非私用 (Private) 成員。
若要繼承自另一個類別
- 加入具有要做為基底類別之類別名稱的 Inherits 陳述式,來做為衍生類別中的第一個陳述式。Inherits 陳述式必須是類別陳述式之後的第一個非註解陳述式。
範例
下列範例定義兩個類別。第一個類別是具有兩個方法的基底類別。第二個類別從基底類別繼承這兩個方法、覆寫第二個方法並且定義名為 Field 的欄位。
Class Class1
Sub Method1()
MsgBox("This is a method in the base class.")
End Sub
Overridable Sub Method2()
MsgBox("This is another method in the base class.")
End Sub
End Class
Class Class2
Inherits Class1
Public Field2 As Integer
Overrides Sub Method2()
MsgBox("This is a method in a derived class.")
End Sub
End Class
Protected Sub TestInheritance()
Dim C1 As New Class1
Dim C2 As New Class2
C1.Method1() ' Calls a method in the base class.
C1.Method2() ' Calls another method from the base class.
C2.Method1() ' Calls an inherited method from the base class.
C2.Method2() ' Calls a method from the derived class.
End Sub
當您執行 TestInheritance 程序時,您會看到下列訊息:
This is a method in the base class.
This is another method in the base class.
This is a method in the base class.
This is a method in a derived class.