繼承架構多型
更新:2007 年 11 月
大部分的物件導向程式設計系統會透過繼承來提供多型。繼承架構多型涉及定義基底類別中的方法,並且用衍生類別中的新實作來覆蓋這些方法。
例如,您可定義 BaseTax 類別,以提供計算某國家營業稅的基準功能。衍生自 BaseTax 的類別,如 CountyTax 或 CityTax,請依適合的情況,來實作像 CalculateTax 一般的方法。
多型 (Polymorphism) 的事實根據是,您不需要知道物件所屬的類別,即可以呼叫屬於任何類別物件的 CalculateTax 方法,該類別衍生自 BaseTax。
下列範例中的 TestPoly 程序示範繼承架構多型:
' %5.3 State tax
Const StateRate As Double = 0.053
' %2.8 City tax
Const CityRate As Double = 0.028
Public Class BaseTax
Overridable Function CalculateTax(ByVal Amount As Double) As Double
' Calculate state tax.
Return Amount * StateRate
End Function
End Class
Public Class CityTax
' This method calls a method in the base class
' and modifies the returned value.
Inherits BaseTax
Private BaseAmount As Double
Overrides Function CalculateTax(ByVal Amount As Double) As Double
' Some cities apply a tax to the total cost of purchases,
' including other taxes.
BaseAmount = MyBase.CalculateTax(Amount)
Return CityRate * (BaseAmount + Amount) + BaseAmount
End Function
End Class
Sub TestPoly()
Dim Item1 As New BaseTax
Dim Item2 As New CityTax
' $22.74 normal purchase.
ShowTax(Item1, 22.74)
' $22.74 city purchase.
ShowTax(Item2, 22.74)
End Sub
Sub ShowTax(ByVal Item As BaseTax, ByVal SaleAmount As Double)
' Item is declared as BaseTax, but you can
' pass an item of type CityTax instead.
Dim TaxAmount As Double
TaxAmount = Item.CalculateTax(SaleAmount)
MsgBox("The tax is: " & Format(TaxAmount, "C"))
End Sub
在本範例中,ShowTax 程序接受 (Accept) 屬於 BaseTax 型別而名為 Item 的參數,但是您也可以傳送諸如 CityTax 之類衍生自 BaseTax 類別的類別。此項設計的優點在於,您可加入衍生自 BaseTax 類別的新類別,而不需要變更 ShowTax 程序中的用戶端程式碼。