Access JumpStart 2.0 | Blog

A Rapid Development Framework for Microsoft Access

What is polymorphism? It’s a concept in object oriented programming that allows you to define different versions of objects that all share some of the same characteristics. In language, an example would be two different cars. A Lamborghini is a car, as is a Ford. Both have the shared characteristics of all cars, but they are not the same car and they have different bodies and engines, but those bodies and engines perform similar tasks like shifting, being different colors, and starting.

In terms of VBA you can create a Class object which defines what characteristics and methods each type of object will share. For a more practical programming example, the FormAuditor class I am working on in the Test Driven Development series I am doing will need to send messages somewhere. Maybe this will be to a database table or maybe to a log file, or maybe even showing the list of changes on a form control.

So each of these different methods of writing could be a separate object, but we don’t know which one the user will want to use. To give them all three options interchangeably, we could create a simple skeleton AuditorOutput class like this:

'AuditorOutput Class
Option Compare Database
Option Compare Explicit

Public Sub WriteAuditorOutput(activeFormAuditor As FormAuditor)
End Sub

Now to utilize this class as an object interface (the definition of the public elements of the series of objects) we would do something like this for the AO_ToDatabase class and the AO_ToFile class:

'AO_ToDatabase Class
Option Compare Database
Option Compare Explicit

Implements AuditorOutput

Private Sub AuditorOutput_WriteAuditorOutput(activeFormAuditor As FormAuditor)
   ' Add Code here to loop over FormAuditor information and save to a database
End Sub

And in this case the AO_ToFile class would be structured the same way, but with code to save the information to a file:

'AO_ToFile Class
Option Compare Database
Option Compare Explicit

Implements AuditorOutput

Private Sub AuditorOutput_WriteAuditorOutput(activeFormAuditor As FormAuditor)
   ' Add Code here to loop over FormAuditor information and save to a file
End Sub

Now in the code where you want to set up a FormAuditor and output to one or both of these the code would look like this:

'Code to use the classes via polymorphism
Dim LogToSomething As AuditorOutput

'Let's say we have a global variable called FormAuditorInstance that has
'collected information on a form and is a FormAuditor object
Set LogToSomething = New AO_ToDatabase
LogToSomething.WriteAuditorOutput FormAuditorInstance

And if you wanted to use a different implementation of AuditorOutput, you could simply specify the Set line to use that object instead:

Set LogToSomething = New AO_ToFile