Click to See Complete Forum and Search --> : Polymorphic object


February 23rd, 2000, 05:56 PM
I want create a Customer object that can be of 2 types -- business and consumer -- each with different properties, but some common.

I want the user of the object to be able to call it without knowing what type of customer will be returned (i.e., just pass in the customer ID).

How do you do this in VB?

Thanks

Chris Eastwood
February 23rd, 2000, 06:05 PM
In VB you'd define a 'base' class containing the standard definition of the object (ie. all the methods and properties, but with no code) - name this class as ICustomer and save it in your project.

Each object that needs this interface can then 'Implement' the interface from that ICustomer Object, eg.

Your ICustomer Class would contain :

option Explicit
'
public property let Name(byval sName as string)
'
End property
'
public property get Name() as string
'
End property
'
public property let Address(byval sAddress as string)
'
End property
'
public property get Address() as string
'
End property




Now your cBusinessCustomer object could contain :


option Explicit
'
Implements ICustomer
'
private msAddress as string
private msName as string
'
private property get ICustomer_Address() as string
ICustomer_Address = msAddress
End property
'
private property let ICustomer_Address(byval RHS as string)
msAddress = RHS
End property
'
private property get ICustomer_Name() as string
ICustomer_Name = msName
End property
'
private property let ICustomer_Name(byval RHS as string)
msName = RHS
End property




To call the routine you would write code such as :


'
Dim oCustomer as ICustomer
'
set oCustomer = new cBusinessCustomer
oCustomer.Name = "Chris"
oCustomer.Address = "http://www.vbcodelibrary.com"




If you wanted to access the properties specifically for the cBusinessCustomer, then you'd have another reference to it :


'
Dim oCustomer as ICustomer
Dim oBCustomer as cBusinessCustomer
'
set oCustomer = new cBusinessCustomer
set oBCustomer = oCustomer
'
oCustomer.Name = "Chris"
oBCustomer.somethingelse = "Whatever"





Chris Eastwood

CodeGuru - the website for developers
http://codeguru.developer.com/vb