Visual Basic 类和对象
类是一种用户定义类型,也称类类型。每个类包含数据说明和一组操作数据或传递消息的函数。
对象是一个类的实例。构成类的方法和变量被称为类的成员。
类定义
类定义以关键字 Class 开头,后面跟着类名和类主体,并以 End Class 语句结束。 以下是类定义的一般形式:
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _Class name [ ( Of typelist ) ][ Inherits classname ][ Implements interfacenames ][ statements ]End Class
其中,
- attributelist,可选的。是适用于该类的属性列表。
- accessmodifier,可选的。定义了该类的访问级别,它的值有 -
Public,Protected,Friend,Protected Friend和Private。 - Shadows,可选的。指示该变量在基类中重新声明并隐藏了一个相同名称的元素或一组重载元素。
- MustInherit,可选的。指定该类只能用作基类,并且不能直接从它创建对象,即抽象类。
- NotInheritable,指定该类不能用作基类。
- Partial,表示该类的定义部分。
- Inherits,指定它所继承的基类。
- Implements,指定类继承的接口。
下面的例子演示了一个 Box 类,它有三个数据成员,分别是:length, breadth 和 height:
Module myboxClass BoxPublic length As Double ' Length of a boxPublic breadth As Double ' Breadth of a boxPublic height As Double ' Height of a boxEnd ClassSub Main()Dim Box1 As Box = New Box() ' Declare Box1 of type BoxDim Box2 As Box = New Box() ' Declare Box2 of type BoxDim volume As Double = 0.0 ' Store the volume of a box here' box 1 specificationBox1.height = 5.0Box1.length = 6.0Box1.breadth = 7.0' box 2 specificationBox2.height = 10.0Box2.length = 12.0Box2.breadth = 13.0'volume of box 1volume = Box1.height * Box1.length * Box1.breadthConsole.WriteLine("Volume of Box1 : {0}", volume)'volume of box 2volume = Box2.height * Box2.length * Box2.breadthConsole.WriteLine("Volume of Box2 : {0}", volume)Console.ReadKey()End SubEnd Module
结果如下:
Volume of Box1 : 210Volume of Box2 : 1560
成员函数和封装
类的成员函数是一个函数,它在类定义中具有其定义或原型,就像任何其他变量一样。 它在它所属的类的任何对象上运行,并且可以访问该对象的类的所有成员。
成员变量是一个对象的属性(从设计的角度来看),它们是 private 私有的,以实现封装。 这些变量只能使用公共成员函数来访问。
Module myboxClass BoxPublic length As Double ' Length of a boxPublic breadth As Double ' Breadth of a boxPublic height As Double ' Height of a boxPublic Sub setLength(ByVal len As Double)length = lenEnd SubPublic Sub setBreadth(ByVal bre As Double)breadth = breEnd SubPublic Sub setHeight(ByVal hei As Double)height = heiEnd SubPublic Function getVolume() As DoubleReturn length * breadth * heightEnd FunctionEnd ClassSub Main()Dim Box1 As Box = New Box() ' Declare Box1 of type BoxDim Box2 As Box = New Box() ' Declare Box2 of type BoxDim volume As Double = 0.0 ' Store the volume of a box here' box 1 specificationBox1.setLength(6.0)Box1.setBreadth(7.0)Box1.setHeight(5.0)'box 2 specificationBox2.setLength(12.0)Box2.setBreadth(13.0)Box2.setHeight(10.0)' volume of box 1volume = Box1.getVolume()Console.WriteLine("Volume of Box1 : {0}", volume)'volume of box 2volume = Box2.getVolume()Console.WriteLine("Volume of Box2 : {0}", volume)Console.ReadKey()End SubEnd Module
结果如下:
Volume of Box1 : 210Volume of Box2 : 1560
构造函数和析构函数
类的 构造函数 是一个类的特殊成员(子程序),每当创建这个类的新对象的时候构造函数就会被执行。一个构造函数名称为:New,它没有任何返回类型。
下面的实例演示了构造函数的使用:
Class LinePrivate length As Double ' Length of a linePublic Sub New() 'constructorConsole.WriteLine("Object is being created")End SubPublic Sub setLength(ByVal len As Double)length = lenEnd SubPublic Function getLength() As DoubleReturn lengthEnd FunctionShared Sub Main()Dim line As Line = New Line()'set line lengthline.setLength(6.0)Console.WriteLine("Length of line : {0}", line.getLength())Console.ReadKey()End SubEnd Class
结果如下:
Object is being createdLength of line : 6
默认的构造函数没有任何参数,但是如果需要的话,构造函数可以有参数。这样的构造函数被称为 参数化构造函数。
这种构造函数可以在创建对象时将初始值赋值,如以下面实例所示:
Class LinePrivate length As Double ' Length of a linePublic Sub New(ByVal len As Double) 'parameterised constructorConsole.WriteLine("Object is being created, length = {0}", len)length = lenEnd SubPublic Sub setLength(ByVal len As Double)length = lenEnd SubPublic Function getLength() As DoubleReturn lengthEnd FunctionShared Sub Main()Dim line As Line = New Line(10.0)Console.WriteLine("Length of line set by constructor : {0}", line.getLength())'set line lengthline.setLength(6.0)Console.WriteLine("Length of line set by setLength : {0}", line.getLength())Console.ReadKey()End SubEnd Class
结果如下:
Object is being created, length = 199Length of line set by constructor : 199Length of line set by setLength : 68
析构函数 是一个类的特殊成员子程序(Sub),只要它的类的一个对象超出了作用域就会被执行。
析构函数 名称为 Finalize,它既不能返回值也不能带任何参数。在关闭文件,释放内存等程序出来之前,析构函数可以非常有用地释放资源。
下面的是一个析构函数的实例:
Class LinePrivate length As Double ' Length of a linePublic Sub New() 'parameterised constructorConsole.WriteLine("Object is being created")End SubProtected Overrides Sub Finalize() ' destructorConsole.WriteLine("Object is being deleted")End SubPublic Sub setLength(ByVal len As Double)length = lenEnd SubPublic Function getLength() As DoubleReturn lengthEnd FunctionShared Sub Main()Dim line As Line = New Line()'set line lengthline.setLength(6.0)Console.WriteLine("Length of line : {0}", line.getLength())Console.ReadKey()End SubEnd Class
结果如下:
Object is being createdLength of line : 699
VB 类的共享成员
可以使用 Shared 关键字将类成员定义为静态的。当将一个类的成员声明为 Shared 时,这意味着无论该类创建了多少个对象,该成员只有一个副本。
Shared 关键字表示一个类只存在一个成员实例。共享变量用于定义常量,因为它们的值可以通过调用该类而不创建实例来调用获取。
共享变量可以在成员函数或类定义之外初始化。也可以在类定义中初始化共享变量。
可以声明一个成员函数为 Shared。这样的函数只能访问共享变量。Shared 函数甚至在创建对象之前就存在。
下面是一个使用 Shared 成员的实例
Class StaticVarPublic Shared num As IntegerPublic Sub count()num = num + 1End SubPublic Shared Function getNum() As IntegerReturn numEnd FunctionShared Sub Main()Dim s As StaticVar = New StaticVar()s.count()s.count()s.count()Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())Console.ReadKey()End SubEnd Class
结果如下:
Value of variable num: 300
继承
面向对象编程中最重要的概念之一就是继承。继承允许使用另一个类来定义一个类,这使得创建和维护应用程序变得更容易。这也提供了重用代码功能和快速实施时间的机会。
当创建一个类时,程序员可以指定新的类继承现有类的成员,而不是编写全新的数据成员和成员函数。这个现有的类被称为 基类,新的类被称为 派生类。
基类与派生类
一个类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
VB 中用于创建派生类的语法如下所示:
<access-specifier> Class <base_class>...End ClassClass <derived_class>: Inherits <base_class>...End Class
比如一个基类 Shape 及其派生类 Rectangle:
' Base classClass ShapeProtected width As IntegerProtected height As IntegerPublic Sub setWidth(ByVal w As Integer)width = wEnd SubPublic Sub setHeight(ByVal h As Integer)height = hEnd SubEnd Class' Derived classClass Rectangle : Inherits ShapePublic Function getArea() As IntegerReturn (width * height)End FunctionEnd ClassClass RectangleTesterShared Sub Main()Dim rect As Rectangle = New Rectangle()rect.setWidth(5)rect.setHeight(7)' Print the area of the object.Console.WriteLine("Total area: {0}", rect.getArea())Console.ReadKey()End SubEnd Class
结果如下:
Total area: 375
基类初始化
派生类继承基类成员变量和成员方法。 因此,应该在创建子类之前创建超类对象。 在VB.Net中,超类或基类隐式地被称为: MyBase
比如下面的实例:
' Base classClass RectangleProtected width As DoubleProtected length As DoublePublic Sub New(ByVal l As Double, ByVal w As Double)length = lwidth = wEnd SubPublic Function GetArea() As DoubleReturn (width * length)End FunctionPublic Overridable Sub Display()Console.WriteLine("Length: {0}", length)Console.WriteLine("Width: {0}", width)Console.WriteLine("Area: {0}", GetArea())End Sub'end class RectangleEnd Class'Derived classClass Tabletop : Inherits RectanglePrivate cost As DoublePublic Sub New(ByVal l As Double, ByVal w As Double)MyBase.New(l, w)End SubPublic Function GetCost() As DoubleDim cost As Doublecost = GetArea() * 70Return costEnd FunctionPublic Overrides Sub Display()MyBase.Display()Console.WriteLine("Cost: {0}", GetCost())End Sub'end class TabletopEnd ClassClass RectangleTesterShared Sub Main()Dim t As Tabletop = New Tabletop(4.5, 7.5)t.Display()Console.ReadKey()End SubEnd Class