article

Classes and Collections - Object Oriented Programming

Email
Submitted on: 1/15/2015 3:07:00 PM
By: Kevin Wiegand (from psc cd)  
Level: Intermediate
User Rating: By 14 Users
Compatibility: VB 5.0, VB 6.0
Views: 2224
 
     This tutorial is designed to give people an idea of what OOP is (Object Oriented Programming) as it is related to Class Modules and Collections. This uses a very simple example of showing how to create/use Class Properties and Methods. It also shows how to use Collections to create a Collection of Classes.

This article has accompanying files
 
				

Classes/Collections Tutorial by Kevin Wiegand. Please download the Zip file that contains the source code if this tutorial is hard to read due to formatting problems.

 

Definitions:

Module

A term used to describe where code is stored within Visual Basic. The three type of modules are (1) Form Modules, (2) Standard Modules, and (3) Class Modules.

Standard Module

A type of Module that contains (or should contain) publically accessible code, in other words, code that is available to any module.

Class (Module)

A type of module that allows you to create objects that contain your customized properties and methods. (The Standard Form (Default:Form1) is actually a Class Module!)

Object

An Object is a Control (TextBox, Label), or it can be a Variable that defines an instance of a Class.

Object Oriented Programming (OOP)

Simply put, OOP is programming with objects.

Collection

A Collection is simply a group of related Objects.

 

Why use Class Modules?

Class modules, as said before, offer a very useful tool - objects. Classes can has multiple instances of its code, and each instances properties/methods belong to that instance only. Standard Module code can only exist once.

 

Lets see an example!

All these definitions, and a short explanation of Class Modules vs Standard Modules - you need to see code, right? OK, start Visual Basic, and start a new Standard Exe Project. Add a Class Module. Rename Project1 to ClassTest; Form1 to frmMain; Class1 to clsClassTest. Paste the following code into each respective module, and then save the project:

 

frmMain:

***Start Copy***

'Require Variable Declaration (I believe that VB.Net already requires that you

'declare all your variables before use - not only does this save memory, but

'it also saves you the hassle of keeping track of things!)

Option Explicit

 

'This defines a Collection, it is empty right now, but we will fill it later :)

Private fClassCollection As New Collection

 

'We'll use Form_Keypress instead of using a bunch of CommandButtons - this is easier

'to do for this example

Private Sub Form_KeyPress(KeyAscii As Integer)

Select Case Chr(KeyAscii)

Case "a"

AddItemToCollection

Case "f"

ReturnNamesByFunction

Case "o"

PrintNames

Case "p"

ReturnNamesByProperty

Case "s"

ReturnNamesBySub

Case " "

ClearCollection

End Select

End Sub

 

Private Sub Form_Load()

'Set initial Form properties, if you want, just set the properties in the Properties

'Pane, and remove this code

Me.ScaleMode = vbPixels

Me.Width = Screen.Width

Me.Height = Screen.Height

Me.Move 0, 0

'Lets us know how many Objects in our Collection (should be zero right now)

Me.Caption = "Total Names in Collection is " & fClassCollection.Count

End Sub

 

Private Sub AddItemToCollection()

'This is what creates a new instance of the Object 'ClassTest'

Dim clsNewClass As New clsClassTest

Dim strName As String

'This sets the Property 'Name' for the ClassTest Object

clsNewClass.Name = InputBox("Enter a name:")

'This adds the newly created Object to the Collection

fClassCollection.Add clsNewClass

'You need to 'close' the new Collection Object in order to add another one.

Set clsNewClass = Nothing

'Lets us know how many Objects in our Collection

Me.Caption = "Total Names in Collection is " & fClassCollection.Count

End Sub

 

Private Sub ClearCollection()

'This creates an Object Variable that will hold references to the Objects in

'the Collection

Dim Obj As Object

For Each Obj In fClassCollection

'This uses the LIFO (Last In First Out) method to remove each Object in the

'Collection, putting in '1' in place of fClassCollection.Count will use the

'LILO (Last In Last Out) method to remove each Object in the Collection.

fClassCollection.Remove fClassCollection.Count

Next Obj

'Lets us know how many Objects in our Collection (should be zero right now)

Me.Caption = "Total Names in Collection is " & fClassCollection.Count

End Sub

 

Private Sub PrintNames()

'This creates an Object Variable that will hold references to the Objects in

'the Collection

Dim Obj As Object

'Clear the form first

Me.Cls

'Print out a litle message

Me.Print "The following " & fClassCollection.Count & " names are in the Collection:" & vbCrLf

For Each Obj In fClassCollection

'This calls the Method to Print the Names currently in the Collection

Obj.PrintName Me

Next Obj

End Sub

 

Private Sub ReturnNamesByFunction()

'This creates an Object Variable that will hold references to the Objects in

'the Collection

Dim Obj As Object

For Each Obj In fClassCollection

'This calls the Method to Return the Names currently in the Collection, and then

'MessageBox it to you, note that this is actually a function instead of a sub as

'from the MsgBoxNames procedure

MsgBox Obj.ReturnName, vbOKOnly + vbInformation

Next Obj

End Sub

 

Private Sub ReturnNamesByProperty()

'This creates an Object Variable that will hold references to the Objects in

'the Collection

Dim Obj As Object

For Each Obj In fClassCollection

'This calls the Method to Return the Names currently in the Collection, and then

'MessageBox it to you, note that this is actually a function instead of a sub as

'from the MsgBoxNames procedure

MsgBox Obj.Name, vbOKOnly + vbInformation

Next Obj

End Sub

 

Private Sub ReturnNamesBySub()

'This creates an Object Variable that will hold references to the Objects in

'the Collection

Dim Obj As Object

For Each Obj In fClassCollection

'This calls the Method to MessageBox out the Names currently in the Collection

Obj.MsgBoxName

Next Obj

End Sub

***End Copy***

 

clsClassTest:

***Start Copy***

Option Explicit

 

'These are internal variables that any one particular instance of this Class can see

'This holds the Name Property

Private fstrName As String

'These hold the Max and Min sizes for the GenerateRandomText Function

Private Const fcMin = 5

Private Const fcMax = 10

 

'This sets the Name Property, it is based off of the Private 'fstrName' Variable

Property Let Name(ByVal strName As String)

If strName = "" Then

'This will call the Private Sub to create a random jumbled string for the

''Name' property if the user add a name that is empty

Randomize Timer

GenerateRandomText (Rnd * (fcMax - fcMin)) + fcMin

Else

fstrName = strName

End If

End Property

 

'This returns the Name Property, it also must be based on the Private 'fstrName' Variable

Property Get Name() As String

Name = fstrName

End Property

 

'This is a simple Private Procedure contained in this Class. Any new instance of this class

'cannot specifically call this Procedure, it can only be called by itself

Private Sub GenerateRandomText(ByVal intSize As Integer)

Dim lngCounter As Long

Dim strTemp As String

Dim bytRnd As Byte

Randomize Timer

For lngCounter = 1 To intSize

bytRnd = CByte((Rnd * (Asc("z") - Asc("a"))) + Asc("a"))

strTemp = strTemp & Chr(bytRnd)

Next lngCounter

Name = strTemp

End Sub

 

'This is a simple Public Procedure contained in this Class. Any new instance of this class

'can specifically call this Procedure

Public Sub MsgBoxName()

MsgBox fstrName, vbOKOnly + vbInformation

End Sub

 

'This is a simple Public Procedure contained in this Class. Any new instance of this class

'can specifically call this Procedure

Public Sub PrintName(ByVal destObj As Object)

'Notice how I called the Property 'Name' instead of referencing the 'fstrName' Variable

destObj.Print Name

End Sub

 

'This is a simple Public Function contained in this Class. Any new instance of this class

'can specifically call this Function

Public Function ReturnName() As String

ReturnName = fstrName

End Function

***End Copy***

 

To use this example you can:

type 'a' to add a name to the collection, leave the input box empty to create a random string

type 'f' to MessageBox the names in the Collection, called using a Function in the Class

type 'o' to print the name in the Collection, called using a Procedure in the Class that contains a Private Procedure within the Class.

type 'p' to MessageBox the names in the Collection, called using the Name Property in the Class

type 's' to MessageBox the names in the Collection, called using a Procedure in the Class

type ' ' (spacebar) to clear the Collection

 

Final Notes:

In this tutorial, you should have learned how to create and use Class Modules. You have learned how to create and use Class Properties, and you have learned how to create and use Class Methods (Methods as Public Procedures, Methods as Public Functions, and Methods as Private Procedures). You have also learned how to use Collections. You have learned how to Add Objects to a Collection, and Remove Objects from a Collection, as well as loop through each Object in a Collection.

If you find any bugs or problems with this tutorial, please let me know! If you have anything to add or comment on, please let me know! If you have found this tutorial helpful, please vote! I can be reached at EinsturzendeNeubauten@hotmail.com, or visit my WebSite at http://www.geocities.com/wieganka, or my mirror site at http://4.41.60.122

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
  3. Scan the source code with Minnow's Project Scanner

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com


Other 4 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.