Polymorphism II (Single Component—Multiple Interfaces)

The second meaning of the term polymorphism is the ability of a component to act as many different types of components. It can do this by implementing multiple interfaces. To illustrate, let’s define a second interface called ISaveToDisk. The purpose of this second interface is to save the balance information to a file. To define this new interface, you would add another class to your project and name it ISaveToDisk. Then you would change the instancing property of this class to 2 - PublicNotCreatable and add a function to your class without any code, as follows:

' Class ISaveToDisk

Option Explicit

Public Sub Save(  )
End Sub

Once the interface is defined, you must implement it. Suppose for the sake of argument that only the CChecking class implemented the interface. In other words, only instances of CChecking could save the balance to disk (no wonder the bank can afford to give such generous interest on savings accounts). The CChecking class would then be modified as follows:

' Class CChecking

Option Explicit

Implements IAccount
Implements ISaveToDisk

Private m_cBalance As Currency

Private Property Get IAccount_Balance(  ) As Currency
    IAccount_Balance = m_cBalance
End Property

Private Sub IAccount_MakeDeposit(ByVal Amount As Currency)
    m_cBalance = m_cBalance + Amount
End Sub

Private Sub ISaveToDisk_Save(  )
    'the implementation of this function is left as an exercise
    'for the reader
End Sub

Suppose that management has asked you to ...

Get COM+ Programming with Visual Basic now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.