Udostępnij za pośrednictwem


Inheritance-Based Polymorphism

Most object-oriented programming systems provide polymorphism through inheritance. Inheritance-based polymorphism involves defining methods in a base class and overriding them with new implementations in derived classes.

For example, you could define a class, BaseTax, that provides baseline functionality for computing sales tax in a state. Classes derived from BaseTax, such as CountyTax or CityTax, could implement methods such as CalculateTax as appropriate.

Polymorphism comes from the fact that you could call the CalculateTax method of an object belonging to any class that derived from BaseTax, without knowing which class the object belonged to.

The TestPoly procedure in the following example demonstrates inheritance-based polymorphism:

' %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

In this example, the ShowTax procedure accepts a parameter named Item of type BaseTax, but you can also pass any of the classes derived from the BaseTax class, such as CityTax. The advantage of this design is that you can add new classes derived from the BaseTax class without changing the client code in the ShowTax procedure.

See Also

Concepts

Interface-Based Polymorphism

Other Resources

Designing an Inheritance Hierarchy