Creating Multiple Instances of the Class

You already learned how to declare and create an instance of a class using the Dim and Set statements. The following example illustrates how you can create multiple instances of the same class.

Public Sub TestMultipleInstances()

'declare both clsCar objects Dim objCar1 As clsCar Dim objCar2 As clsCar

'instantiate new instances for each Set objCar1 = New clsCar Set objCar2 = New clsCar

'set the VehicleId property for the first instance 'of clsCar and then call the previously created 'update method as an example objCar1.VehicleIdNumber = "98765" objCar1.Update

'set the VehicleId property for the second instance 'of clsCar and then call the previously created 'update method as an example objCar2.VehicleIdNumber = "12345" objCar2.Update

End Sub

Notice how two different clsCar objects are declared and instantiated. The VehicleIdNumber property of each instance of the class is assigned, and the Update method of each instance of the class is called.

As shown in Figure 4.12, the Immediate Window displays the messages generated from the Update method indicating the record was being updated for each respective instance of the class.

In mediate

Form f rmCarDetaiis .Te3tMultipieInstance3

-

clsCar.Update method

Record being updated for Vebicleld:

93765

clsCar.Update method

Record fceincr updated for Vehicleld:

12 34 5

n

±J_I

111

Figure 4.12

0 0

Post a comment