基于继承的多态性
更新:2007 年 11 月
大部分面向对象的编程系统都通过继承提供多态性。基于继承的多态性涉及在基类中定义方法并在派生类中使用新实现重写它们。
例如,可以定义一个类 BaseTax,该类提供计算某个州/省的销售税的基准功能。从 BaseTax 派生的类(如 CountyTax 或 CityTax)可以根据相应的情况实现方法,如 CalculateTax。
多态性来自这样一个事实:可以调用属于从 BaseTax 派生的任何类的某个对象的 CalculateTax 方法,而不必知道该对象属于哪个类。
下面示例中的 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 过程接受 BaseTax 类型的名为 Item 的参数,但还可以传递从该 BaseTax 类派生的任何类,如 CityTax。这种设计的优点在于可添加从 BaseTax 类派生的新类,而不用更改 ShowTax 过程中的客户端代码。