VB.類和對象

當定義一個類時,就定義了一個數據類型的藍圖(或模板)。這實際上並沒有定義任何數據,但它確實定義了類名和含義,即該類的一個對象將包含哪些內容以及可以在這樣的對象上執行哪些操作。

對象是一個類的實例。構成類的方法和變量被稱爲類的成員。

類定義

類定義以關鍵字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 FriendPrivate,這是一個可選項。
  • Shadows 指示該變量在基類中重新聲明並隱藏了一個相同名稱的元素或一組重載元素,這是一個可選項。
  • MustInherit 指定該類只能用作基類,並且不能直接從它創建對象,即抽象類,這是一個可選項。
  • NotInheritable 指定該類不能用作基類。
  • Partial 表示該類的定義部分。
  • Inherits 指定它所繼承的基類。
  • Implements 指定類繼承的接口。

下面的例子演示了一個Box類,它有三個數據成員,分別是:length, breadthheight

Module mybox
   Class Box
      Public length As Double   ' Length of a box '
      Public breadth As Double   ' Breadth of a box '
      Public height As Double    ' Height of a box '
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box '
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box '
      Dim volume As Double = 0.0     ' Store the volume of a box here '
      ' box 1 specification '
      Box1.height = 5.0
      Box1.length = 6.0
      Box1.breadth = 7.0
       ' box 2 specification '
      Box2.height = 10.0
      Box2.length = 12.0
      Box2.breadth = 13.0
      'volume of box 1 '
      volume = Box1.height * Box1.length * Box1.breadth
      Console.WriteLine("Volume of Box1 : {0}", volume)
      'volume of box 2 '
      volume = Box2.height * Box2.length * Box2.breadth
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc mybox.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>mybox.exe
Volume of Box1 : 210
Volume of Box2 : 1560

成員函數和封裝

一個類的成員函數是一個函數,它在類定義中具有其定義或原型,就像任何其他變量一樣。 它在它所屬的類的任何對象上運行,並且可以訪問該對象的類的所有成員。

成員變量是一個對象的屬性(從設計的角度來看),它們是保密的,以實現封裝。 這些變量只能使用公共成員函數來訪問。

讓我們來看看上面的概念設置和獲得不同類成員的值:

Module MemberFunctions
   Class Box
      Public length As Double   ' Length of a box '
      Public breadth As Double   ' Breadth of a box'
      Public height As Double    ' Height of a box'
      Public Sub setLength(ByVal len As Double)
          length = len
      End Sub
      Public Sub setBreadth(ByVal bre As Double)
          breadth = bre
      End Sub
      Public Sub setHeight(ByVal hei As Double)
          height = hei
      End Sub
      Public Function getVolume() As Double
          Return length * breadth * height
      End Function
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box'
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box'
      Dim volume As Double = 0.0     ' Store the volume of a box here'

     ' box 1 specification'
      Box1.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)

      'box 2 specification'
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)

      ' volume of box 1'
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2'
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc MemberFunctions.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
F:\worksp\vb.net\classes_objects>MemberFunctions.exe
Volume of Box1 : 210
Volume of Box2 : 1560

構造函數和析構函數

一個類的構造函數是一個類的特殊成員子程序,每當創建這個類的新對象的時候構造函數就會被執行。一個構造函數名稱爲:New,它沒有任何返回類型。

以下程序演示了構造函數的概念和使用:

Module MemberFunctions
   Class Box
      Public length As Double   ' Length of a box '
      Public breadth As Double   ' Breadth of a box'
      Public height As Double    ' Height of a box'
      Public Sub setLength(ByVal len As Double)
          length = len
      End Sub
      Public Sub setBreadth(ByVal bre As Double)
          breadth = bre
      End Sub
      Public Sub setHeight(ByVal hei As Double)
          height = hei
      End Sub
      Public Function getVolume() As Double
          Return length * breadth * height
      End Function
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box'
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box'
      Dim volume As Double = 0.0     ' Store the volume of a box here'

     ' box 1 specification'
      Box1.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)

      'box 2 specification'
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)

      ' volume of box 1'
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2'
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc Line.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>Line.exe
Object is being created
Length of line : 6

默認的構造函數沒有任何參數,但是如果需要的話,構造函數可以有參數。這樣的構造函數被稱爲參數化的構造函數。這種技術可以在創建對象時將初始值賦值,如以下示例所示:

Class Line2
   Private length As Double    ' Length of a line '
   Public Sub New(ByVal len As Double)   'parameterised constructor '
      Console.WriteLine("Object is being created, length = {0}", len)
      length = len
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub

   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line2 = New Line2(199.0)
      Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
      'set line length '
      line.setLength(68.0)
      Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc Line2.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>Line2.exe
Object is being created, length = 199
Length of line set by constructor : 199
Length of line set by setLength : 68

析構函數是一個類的特殊成員子程序(Sub),只要它的類的一個對象超出了作用域就會被執行。

析構函數名稱爲Finalize,它既不能返回值也不能帶任何參數。在關閉文件,釋放內存等程序出來之前,析構函數可以非常有用地釋放資源。

析構函數不能被繼承或重載。

下面的例子演示瞭如何使用析構函數:

Class Line3
   Private length As Double    ' Length of a line'
   Public Sub New()   'parameterised constructor'
      Console.WriteLine("Object is being created")
   End Sub
   Protected Overrides Sub Finalize()  ' destructor'
      Console.WriteLine("Object is being deleted")
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line3 = New Line3()
      'set line length '
      line.setLength(699.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc Line3.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.

......

F:\worksp\vb.net\classes_objects>Line3.exe
Object is being created
Length of line : 699

VB.Net類的共享成員

可以使用Shared關鍵字將類成員定義爲靜態的。當將一個類的成員聲明爲Shared時,這意味着無論該類創建了多少個對象,該成員只有一個副本。

Shared關鍵字表示一個類只存在一個成員實例。共享變量用於定義常量,因爲它們的值可以通過調用該類而不創建實例來調用獲取。

共享變量可以在成員函數或類定義之外初始化。也可以在類定義中初始化共享變量。

可以聲明一個成員函數爲Shared。這樣的函數只能訪問共享變量。Shared函數甚至在創建對象之前就存在。

以下示例演示了共享(Shared)成員的使用:

Class StaticVar
   Public Shared num As Integer
   Public Sub count()
      num = num + 100
   End Sub
   Public Shared Function getNum() As Integer
      Return num
   End Function
   Shared 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 Sub
End Class

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc StaticVar.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.

.....

F:\worksp\vb.net\classes_objects>StaticVar.exe
Value of variable num: 300

繼承

面向對象編程中最重要的概念之一就是繼承。繼承允許使用另一個類來定義一個類,這使得創建和維護應用程序變得更容易。這也提供了重用代碼功能和快速實施時間的機會。

當創建一個類時,程序員可以指定新的類繼承現有類的成員,而不是編寫全新的數據成員和成員函數。這個現有的類被稱爲基類,新的類被稱爲派生類。

基礎派生類

一個類可以從多個類或接口派生,這意味着它可以從多個基類或接口繼承數據和函數。
VB.Net中用於創建派生類的語法如下所示:

<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class

考慮一個基類Shape及其派生類Rectangle

' 定義基類 '
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' 子類或派生類 '
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(15)
      rect.setHeight(25)
      ' Print the area of the object. '
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub    
End Class

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc BaseDerived.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
.....
F:\worksp\vb.net\classes_objects>BaseDerived.exe
Total area: 375

基類初始化

派生類繼承基類成員變量和成員方法。 因此,應該在創建子類之前創建超類對象。 在VB.Net中,超類或基類隱式地被稱爲:MyBase

以下程序演示了這一點:


' 定義基類 '
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' 子類或派生類 '
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(15)
      rect.setHeight(25)
      ' Print the area of the object. '
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub    
End Class

執行上面示例代碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc BaseClassInitialization.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>BaseClassInitialization.exe
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
0 條評論,你可以發表評論,我們會進行改進
Comment author placeholder