如何:创建派生类
更新:2007 年 11 月
Inherits 语句导致类继承指定类的所有非私有成员。
从另一个类继承
- 添加一条 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.