Share via


継承ベースのポリモーフィズム

更新 : 2007 年 11 月

ほとんどのオブジェクト指向プログラミング システムは、継承を通じてポリモーフィズムを提供しています。継承ベースのポリモーフィズムでは、基本クラスでメソッドを定義し、派生クラスで新しい実装を使用してメソッドをオーバーライドします。

たとえば、消費税を計算するための基本機能を提供する BaseTax というクラスを定義したとします。CountyTax や CityTax などの BaseTax の派生クラスでは、必要に応じて 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 など) を渡すこともできます。このデザインの利点は、ShowTax プロシージャのクライアント コードを変更することなく、BaseTax クラスから派生した新しいクラスを追加できるという点にあります。

参照

概念

インターフェイス ベースのポリモーフィズム

その他の技術情報

継承階層のデザイン