Classes and Objects
An object is an encapsulation of data, and methods (procedures) that act on the data. The details of the data structures used and the implementation of the methods are hidden inside the object. All the programmer needs to know is what tasks the object can perform, and the parameters required by these tasks.
Control objects are predefined objects that can be created using the Visual Basic toolbox, such as text boxes, command buttons and other controls. No matter how many text boxes you create on a form, they all have the same properties and methods. Essentially, a class is a template from which an object is created, and specifies the properties and methods that will be common to all objects that are created from it. Each text box is therefore an instance of the class TextBox, for which you can set the properties or invoke the methods.
The value of a property is manipulated by two procedures, one to set the value (Let) and the other to retrieve the value (Get). These procedures are sometimes referred to as accessor methods.
Code objectsmust be created by the programmer, and are instances of user-defined types that are defined in a separate class module. Like control objects, they have properties and methods and can respond to events. The set of properties, methods, and events for a class is called the class interface. Two (or more) different classes may have the same interface, and carry out identical tasks, even though they carry out the task differently. The occurrence of two or more classes that have behaviors with the same name and functionality but different implementations is called polymorphism.
Events are declared in the general declarations section of class module with a statement of the form:
Public Event UserDefinedEvent (arg1, arg2, ...)
and triggered with a RaiseEvent statement. The statement that declares the object in the form's code must include the keyword WithEvents in order for the events coming from the object to be processed.
When Visual Basic is an object-oriented programming language. Applications communicate with objects through the properties and methods they expose, and the events they raise. When you program with Visual Basic, you are programming objects, such as the controls you place on a form, by manipulating their properties and calling their methods. The action takes place within the object's event procedures, which are executed in response to the occurrence of some event. Events are said to be raised (in other words they are considered to have occurred) when certain conditions are met.
The relationship between an object and the application
Example 1
Open a new Visual Basic project, save it to a new folder, and create a form similar to the one illustrated below.
The "frmStudents" form
| Properties for "frmStudents" form | |||
| Control | Name | Caption | Additional Properties |
| Form | frmStudents | Students | |
| Label | lblTitle | Create Student Record | Alignment = 2 - Center |
| Label | lblName | Name | Alignment = 1 - Right Justify |
| TextBox | txtName | ||
| Label | lblNumber | Number | Alignment = 1 - Right Justify |
| TextBox | txtNumber | ||
| Button | cmdEnter | Enter Details | |
| Button | cmdDisplay | Display Details | |
| PicturePox | picStudent | ||
| Button | cmdQuit | Exit | |
Creating the Student class
It is a convention to precede the name of a class with the letter 'C'. We will therefore use the name CStudent. Use the following steps to create the CStudent class:
- From the Project menu, select Add Class Module.
- Double-click on Class Module in the Add Class Module dialog box.
- If the Properties window is not visible, press F4 to display it. (Note that the class has the default name Class1.)
- Change the setting of the Name property to CStudent.
- Type the following lines into the code module:
Private mName As String
Private mNumber As String
'These are the member variables used to hold data.
'The word Private means they cannot be accessed directly. - From the Tools menu, click on Add Procedure.
- Type Name into the Name text box, select the
Property radio button in the Type box, and click on
OK. The following code will appear in the class module window:
Public Property Get Name() As String
End Property
Public Property Let Name(ByVal vNewValue As Variant)
End Property - Change the word Variant in both procedures to
String, and the word vNewValue
in the second procedure to vName, and add code to the procedures as shown below:
Public Property Get Name() As String
Name = mName
End Property
Public Property Let Name(ByVal vName As Variant)
mName = vName
End Property
'The first procedure retrieves the value of the variable mName
'The second procedure assigns a value to mName - Create the procedures that will be used to retrieve and assign values to the
variable mNumber as follows:
Public Property Get Number() As String
Number = mNumber
End Property
Public Property Let Number(ByVal vNumber As Variant)
mNumber = vNumber
End Property - From the File menu, click on Save CStudent As and save the class module with the name CStudents.cls. The .cls extension is used for files holding class modules.
Using the Student class
We can now write a program that creates an object that is an instance of the CStudent class, and uses the Property Let and Property Get procedures to assign values to and retrieve values from the member variables. Enter the following code in the form's code window:
Private Student As CStudent
Private Sub Form_Load()
Set Student = New CStudent
End Sub
Private Sub cmdEnter_Click()
Student.Name = txtName
Student.Number = txtNumber
txtName.Text = ""
txtNumber.Text = ""
End Sub
Private Sub cmdDisplay_Click()
picStudent.Cls
picStudent.Print "Student Name:"
picStudent.Print Student.Name
picStudent.Print
picStudent.Print "Student Number:"
picStudent.Print Student.Number
End Sub
Private Sub cmdQuit_Click()
End
End Sub
Run the program and enter a student name and number, press the Enter Details button to send the data to the object, and press the Display Details button to retrieve the details from the object and display the student's name and number.
The Initialize event procedure
The Object drop-down combo box in a class module window displays two items, General and Class (see below).
The class module window
When you click on Class, the following template appears:
Private Sub Class_Initialize()
End Sub
This procedure is automatically invoked when an object is created from the class, and can be used to set default values for member variables, or to create other objects associated with this object. The counterpart to Initialize is the Terminate event procedure which has a similar format, and is automatically invoked when all references to the object are set to Nothing, or when the object falls out of scope (an object falls out of scope, remember, when the procedure that created it is exited). This procedure can be used to set any objects you may have created using the class module to Nothing.
Class relationships
Three relationships can exist between classes:
- Use - one class uses another class if it manipulates or creates objects of that class. In general, class A uses class B if an object of class B is sent a message by a property or method of class A, or a method or property of class A returns, receives, or creates objects of class B.
- Containment - class A contains class B when a member variable of class A has class B as its type.
- Inheritance - this is the process by which one class (the child class), inherits the properties, methods, and events of another class (the parent class). Note that Visual Basic does not support the strict academic definition of inheritance.
Objects interact through use and containment.