程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> Visual Basic語言 >> VB.NET >> vb.net中用繼承實現多態性

vb.net中用繼承實現多態性

編輯:VB.NET

大部分面向對象的程序開發系統都是通過繼承來實現多態。比如說跳蚤類和狗類都是從動物類繼承過來的。為了突出每一種動物走動的特點,則每一種特定動物類都要重載動物類的"Move"方法。
多態性的問題是因為用戶可以需要在還不知道是要對哪種特定動物進行處理的時候,就要調用多種從動物類中派生出來的特定的動物類中的"Move"方法。
在下面的這個TestPolymorphism過程中,用繼承來實現多態性:

MustInherit Public Class Amimal '基本類
    MustOverride Public Sub Bite(Byval What As Object)
    MustOverride Public Sub Move(ByRef Distance As Double)
End Class
Public Class Flea
    Inherits Amimal
    Overrides Sub bite(Byval What As Object)
         'Bite something
    End Sub
    Overrides Sub Move(ByRef Distance As Double)
         distance=Distance+1
    End Sub
End Class

Public Class Dog
    Inherits Animal
    Overrides Public Sub bite(Byval What As Object)
        'Bite something
    End Sub
    Overrides Sub Move(ByRef Distance As Double)
        distance=Distance+100
    End Sub
End Class

Sub TestPolymorphism()
    Dim aDog As New Dog()
    Dim aFlea As New Flea()
    UseAnimal(aFlea) 'Pass a flea object to UseAnimal procedure
    UseAnimal(aDog)  'Pass a Dog object to UseAnimal procedure
End Sub

Sub UseAnimal(Byval AnAnimal As Animal)
    Dim distance As Double=0
    'UseAnimal does not care what kind of animal it is using
    'The Move method of both the Flea and the Dog are inherited
    'from the Animal class and can be used interchangeably.
    AnAniml.Move(distance)
    If distance=1 Then
       MessageBox.Show("The animal moved:"&CStr(distance)&_
                      "units,so it must be a Flea.")
    ElseIf distance>1 Then
       MessageBox.Show("The animal moved:"&CStr(distance)&_
                      "units,so it must be a Dog.")
    End IF
End Sub
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved