Introduction to Classes and Objects |
|
Classes Fundamentals
Introduction
A class is a technique of using one variable or a group of variables in one unit to describe an object.
Practical Learning: Introducing Classes
Creating a Class
To help you create a class, Microsoft Visual Basic provides a special version of a module named a class module. To create a class:
As mentioned for the regular module, Microsoft Visual Basic would give a default name to the module. Normally, you should name the module based on the name you want for your class. To name or re-name a class module, click its name in the Project window. In the Properties window, click (Name) or its text box. Type the desired name and press Enter. After creating and naming the module, it becomes a class.
Practical Learning: Creating a Class in Microsoft Access
The Contents, Body, and Members of a Class
The whole area of a class module, that is, the whole content of the file is referred to as the body of the class. All things in the module, that is, all the object inside the document are (considered as) the members of the class.
The Member Variables of a Class
A class is a combination of values or variables. To create those values or variables, declare each variable in the module.
Practical Learning: Adding Members to a Class
Dim EmployeeeNumber As Long Dim FirstName As String Dim LastName As String Dim HourlySalary As Double
Public PayrollID As Long Public EmployeeeNumber As Long Public Monday As Double Public Tuesday As Double Public Wednesday As Double Public Thursday As Double Public Friday As Double Public Saturday As Double Public Sunday As Double
Creating an Object
Introduction
After creating a class, to use it in your project, you must declare a variable for it. This is also referred to as creating an object or creating an instance of the class. To create an object, use the Dim keyword followed by a name for the object, the As keyword, and the name of the class. Here is an example:
Private Sub cmdSubmit_Click()
Dim staff As Employee
End Sub
Allocating Computer Memory for an Object
To let the computer hold the values of an object, you must allocate some computer memory for it. To assist you with this, the Visual Basic language provides an operator named New. To use it, assign it to the variable and follow it with the name of the class. Here is an example:
Private Sub cmdSubmit_Click()
Dim staff As Employee
staff = New Employee
End Sub
Instead of first declaring the variable before allocating memory for it, you can take care of this directly when declaring the variable by inserting the New operator between the As keyword and the name of the class.
Practical Learning: Creating an Object
Private Sub cmdCreate_Click()
Dim staff As New Employee
End Sub
Accessing a Member of a Class
The Public Members of a Class
If you use the Dim keyword to declare a variable in the body (as a member) of a class, the member is said to be hidden. Such a member cannot be accessed outside the class but it can be accessed by the other members of the class, only in the module. For a member to be accessible outside the class, the member must be made public. To make this happen, use the Public keyword in place of Dim to create the member. This is not a requirement. You will (know to) decide when a member must be public and when not.
Practical Learning: Making Members Accessible
Public EmployeeNumber As Long Public FirstName As String Public LastName As String Public HourlySalary As Double
The Period Operator: .
To access a member of a class outside the class, type the name of the variable, followed by a period, followed by the name of the member you want to access. Once you have accessed a member, you can use it. For example, you can assign a value to it.
Remember that, to create more than one statement on the same line, you can use the colon operator. Here is an example:
Private Sub cmdCreate_Click() Dim staff As New Employee staff.EmployeeNumber = 29739: staff.HourlySalary = 18.85 staff.FirstName = "Gregory": staff.LastName = "Plane" txtEmployeeNumber = staff.EmployeeNumber: txtFirstName = staff.FirstName txtLastName = staff.LastName: txtHourlySalary = staff.HourlySalary End Sub
The Members of an Object in the Code Editor: Using the IntelliSence
When writing code, the Code Editor is equipped to assist you with the names of the members of a class. When you type the name of an object followed by the period operator, the available members would appear in a list. Here is an example:
This feature is called IntelliSense. It works on most or all objects. If the list is long, you can start typing the lettters until the desired option appears. When using the IntelliSence, if you see the member you want:
Practical Learning: Accessing the Members of an Object
Private Sub cmdCreate_Click()
Dim staff As New Employee
staff.EmployeeNumber = 29739
staff.FirstName = "Gregory"
staff.LastName = "Plane"
staff.HourlySalary = 18.85
txtEmployeeNumber = staff.EmployeeNumber
txtFirstName = staff.FirstName
txtLastName = staff.LastName
txtHourlySalary = staff.HourlySalary
End Sub
Private Sub cmdCalculateTimeWorked_Click()
Dim pay As New Payroll
Dim timeWorked As Double
pay.PayrollID = 100001
pay.EmployeeeNumber = 29739
pay.Monday = 8#
pay.Tuesday = 9.5
pay.Wednesday = 8.5
pay.Thursday = 8#
pay.Friday = 10#
pay.Saturday = 0#
pay.Sunday = 0#
timeWorked = pay.Monday + pay.Tuesday + pay.Wednesday + _
pay.Thursday + pay.Friday + pay.Saturday + pay.Sunday
txtPayrollID = pay.PayrollID
txtEmployeeNumber = pay.EmployeeeNumber
txtTimeWorked = timeWorked
End Sub
Static Classes and Static Objects
A class is referred to as static if there is no need to declare a variable in order to access the members of that class. This means that you must use the class directly in your code and access its members using the period operator.
Allocating and De-Allocating Memory for an Object
Creating a Reference to an Object
We saw that, when creating an object, that is, when declaring a variable for it, you can use the New operator to ask the compiler to allocate memory for it. This is done if you want to immediately use the object. Sometimes you can declare a variable but are not ready to use the object. In that case, you don't have to allocate memory for it. You can declare the variable without using the New operator. Here is an example:
Private Sub cmdVariable_Click()
Dim pay As Payroll
End Sub
In this case, when you are ready to use the object, you must allocate memory for it. This time, you must use another operator named Set but precede the name of the class with New. Here is an example:
Private Sub cmdVariable_Click()
Dim pay As Payroll
Set pay = New Payroll
End Sub
From there, you can use the object normally.
De-Allocating Memory Object
Some objects don't use much computer resources. Others do, such as those that use and manipulate many files. Therefore, it is recommended that, after using an object in a procedure, you should ask the compiler to remove the object from memory so that other objects can use the resources your object was using. To assist you with this, the Visual Basic language provides an object named Nothing. To use, assign it to the object using the Set operator.
You can also de-allocate memory even you didn't use the Set operator to initialize the object.
Practical Learning: Allocating and De-Allocating Memory for an Object
Private Sub cmdCalculateTimeWorked_Click()
Dim pay As New Payroll
Dim timeWorked As Double
pay.PayrollID = 100001
pay.EmployeeeNumber = 29739
pay.Monday = 8#
pay.Tuesday = 9.5
pay.Wednesday = 8.5
pay.Thursday = 8#
pay.Friday = 10#
pay.Saturday = 0#
pay.Sunday = 0#
timeWorked = pay.Monday + pay.Tuesday + pay.Wednesday + _
pay.Thursday pay.Friday + pay.Saturday + pay.Sunday
txtPayrollID = pay.PayrollID
txtEmployeeNumber = pay.EmployeeeNumber
txtTimeWorked = timeWorked
Set pay = Nothing
End Sub
Private Sub cmdCreate_Click() Dim staff As Employee Set staff = New Employee staff.EmployeeNumber = 29739 staff.FirstName = "Gregory" staff.LastName = "Plane" staff.HourlySalary = 18.85 txtEmployeeNumber = staff.EmployeeNumber txtFirstName = staff.FirstName txtLastName = staff.LastName txtHourlySalary = staff.HourlySalary Set staff = Nothing End Sub
Classes and Procedures
A Function that Returns an Object
A function can be made to return an object. When creating such a function, after its parentheses, type the As keyword followed by a space and the name of the class. Here is an example:
Private Function CreateEmployee() As Employee
End Function
Passing an Object to a Procedure
A class can be passed to a procedure as parameter. In this case, provide the name of the class for the parameter in the parentheses of the procedure. You don't have to use the parameter in the body of the function. Otherwise, you can use the parameter in the body of the procedure. To access a member of the class, type the name of the parameter followed by a period and the name of the member.
Practical Learning: Passing an Object to a Procedure
Private Sub ShowEmployee(staff As Employee) txtEmployeeNumber = staff.EmployeeNumber txtFirstName = staff.FirstName txtLastName = staff.LastName txtHourlySalary = staff.HourlySalary End Sub
Private Sub ShowEmployee(staff As Employee) txtEmployeeNumber = staff.EmployeeNumber txtFirstName = staff.FirstName txtLastName = staff.LastName txtHourlySalary = staff.HourlySalary End Sub Private Sub cmdCreate_Click() Dim staff As Employee Set staff = New Employee staff.EmployeeNumber = 38405 staff.FirstName = "Jeannette" staff.LastName = "Gibson" staff.HourlySalary = 24.27 ShowEmployee staff Set staff = Nothing End Sub
Passing Many Objects to a Procedure
As mentioned for regular types, a procedure can take more than one parameter. One of the parameters can be a class type while the other(s) is(are) (a) regular type(s). In the body of the procedure, you don't have to use any of the parameters, or you can use one of them or all of them.
You can create a procedure that takes more than one parameter where all parameters are class types. Once again, in the body of the procedure, you can ignore one of the parameters.
Practical Learning: Passing Many Objects to a Procedure
Public SerialNumber As String Public Make As String Public Model As String Public Price As String
Public Cost As Double Public SalvageValue As Double Public EstimatedLife As Integer
Function Calculate(ByVal item As Machine, ByVal estimate As Depreciation) As Double Dim value As Double value = (estimate.Cost - estimate.SalvageValue) / estimate.EstimatedLife Calculate = value End Function
Function Calculate(ByVal item As Machine, ByVal estimate As Depreciation) As Double
Dim value As Double
value = (estimate.Cost - estimate.SalvageValue) / estimate.EstimatedLife
Calculate = value
End Function
Private Sub cmdCalculateDepreciation_Click()
Dim value As Double
Dim dep As New Depreciation
dep.Cost = 5000
dep.SalvageValue = 500
dep.EstimatedLife = 5
value = Calculate(Nothing, dep)
txtMachineCost = dep.Cost
txtSalvageValue = dep.SalvageValue
txtEstimatedLife = dep.EstimatedLife
txtDepreciation = value
End Sub
Introduction to the Methods of a Class
Overview
A procedure or a function can be created in the body, as a member, of a class module to perform actions for, or on behalf of, the class. Such a procedure or member function is called a method.
To create a method, in the body of a class, use the same formulas as for procedures and functions. Here is an example of a function method:
Public Cost As Double
Public SalvageValue As Double
Public EstimatedLife As Integer
Function Calculate() As Double
End Function
When you have created a member variable in a class module, it is available to all methods of the same class. This means that, to use it from a method of the same class, you don't have to declare a variable for the class.
Practical Learning: Introducing the Methods of a Class
Public Cost As Double Public SalvageValue As Double Public EstimatedLife As Integer Function Calculate() As Double Calculate = (Cost - SalvageValue) / EstimatedLife End Function
A Public Method
A method is said to be hidden if it cannot be accessed outside the class but can be accessed only by other members of the same class, in the body of the class. A method is referred to as public if it can be accessed by objects outside the class. To specify that a method is public, precede it with the Public keyword.
Practical Learning: Making a Member Accessible Outside the Class
Public Cost As Double
Public SalvageValue As Double
Public EstimatedLife As Integer
Public Function Calculate()
Calculate = (Cost - SalvageValue) / EstimatedLife
End Function
Accessing a Method Outside the Class
To access a method outside of its class, use the same period operator used for member variables.
Practical Learning: Accessing a Method Outside the Class
Private Sub cmdCalculateDepreciation_Click()
Dim d As Double
Dim vehicle As New Depreciation
vehicle.Cost = 45800
vehicle.SalvageValue = 6000
vehicle.EstimatedLife = 6
d = vehicle.Calculate()
txtMachineCost = vehicle.Cost
txtSalvageValue = vehicle.SalvageValue
txtEstimatedLife = vehicle.EstimatedLife
txtDepreciation = d
Set vehicle = Nothing
End Sub
Class Construction and Termination
Object Initialization
When you declare a variable of a class, a special method must be called to initialize the members of that class. In most computer languages, this method is called a constructor. To let you create a special method that can be used to initialize the members of a class, open the class method in Microsoft Visual Basic. In the Object combo box, select Class. In the Procedure combo box, select Initialize. The skeleton code of a private procedure named Class_Initialize would be generated. In the body of that method, you can access the desired member variable and initialize it any way you want.
The Class_Initialize() method is automatically used and called behind the scenes when you create an object. As a result, you should never call that method.
Practical Learning: Initialyzing a Class
Private Sub Class_Initialize() End Sub
Public Cost As Double
Public SalvageValue As Double
Public EstimatedLife As Integer
Function Calculate() As Double
Calculate = (Cost - SalvageValue) / EstimatedLife
End Function
Private Sub Class_Initialize()
Cost = 0#
SalvageValue = 0#
EstimatedLife = 0
End Sub
Object Termination
When an object has been used and is not needed anymore, it must be removed from the computer memory. To assist you with this, the VBA provides a special method for every class and it its named Class_Terminate. To let you create this special method, open the class method in Microsoft Visual Basic. In the Object combo box, select Class. In the Procedure combo box, select Terminate. The skeleton code would be generated for you.
Practical Learning: Terminating a Class
Private Sub Class_Terminate() End Sub
Using an Object With Me
With a Class Instance
To access the members of a class using an object, you can use the With keyword. Type it followed by the name of the variable. Create a new line and type End With. The section between the With variable-name line and the End With line is the body of the With statement. In that body, to access a member of the class, type the period operator followed by the desired member.
Practical Learning: Accessing the Members With an Object
Private Sub ShowEmployee(staff As Employee) txtEmployeeNumber = staff.EmployeeNumber txtFirstName = staff.FirstName txtLastName = staff.LastName txtHourlySalary = staff.HourlySalary End Sub Private Sub cmdCreate_Click() Dim staff As Employee Set staff = New Employee With staff .EmployeeNumber = 20864 .FirstName = "Paula" .LastName = "Henley" .HourlySalary = 14.88 End With ShowEmployee staff Set staff = Nothing End Sub
Private Sub cmdCalculateDepreciation_Click()
Dim d As Double
Dim vehicle As New Depreciation
With vehicle
.Cost = 128500
.SalvageValue = 30000
.EstimatedLife = 10
d = .Calculate()
txtMachineCost = .Cost
txtSalvageValue = .SalvageValue
txtEstimatedLife = .EstimatedLife
txtDepreciation = d
End With
Set vehicle = Nothing
End Sub
To let you access the member(s) of a class module while inside the module, the Visual Basic language provides a special object named Me. When using Me, you can access any member of a class within any method of the same module.
Because Me is an object, you can assign it to a variable that refers to an object of the same class. Here is an example:
Option Compare Database
Option Explicit
Public ItemNumber As Long
Public ItemName As String
Public Size As String
Public UnitPrice As Double
Public Function CalculateDiscountAmount(Optional ByVal DiscountRate As Double = 20#) As Double
CalculateDiscountAmount = UnitPrice * DiscountRate / 100#
End Function
Public Sub Examine()
Dim inside
Dim inside = Me
End Sub
You can also compare an object to Me to find out what that object represents.
There are rules you must follow when using Me:
Practical Learning: Using Me
Public Cost As Double Public SalvageValue As Double Public EstimatedLife As Integer Function Calculate() As Double Calculate = (Me.Cost - Me.SalvageValue) / Me.EstimatedLife End Function Private Sub Class_Initialize() Me.Cost = 0# Me.SalvageValue = 0# Me.EstimatedLife = 0 End Sub Private Sub Class_Terminate() End Sub
Private Sub cmdCalculateDepreciation_Click() Dim d As Double Dim vehicle As New Depreciation With vehicle .Cost = 4500 .SalvageValue = 500 .EstimatedLife = 3 d = .Calculate() Me.txtMachineCost = .Cost Me.txtSalvageValue = .SalvageValue Me.txtEstimatedLife = .EstimatedLife Me.txtDepreciation = d End With Set vehicle = Nothing End Sub
Methods and Arguments
Introduction
Like regular procedures, a method can have one or more parameters. The rules are the same as those applied to regular procedures or functions. Because a method has direct access to all regular members of its class, you don't have to create a parameter for a member variable of the same class. You would need a parameter only if an external value would be passed to the method.
Practical Learning: Using Parameters in a Method
Public EmployeeNumber As Long
Public FirstName As String
Public LastName As String
Public HourlySalary As Double
Public Function CalculateNetPay(ByVal time As Double) As Double
CalculateNetPay = HourlySalary * time
End Function
Private Sub cmdCreate_Click() Dim hSalary As Double Dim timeWorked As Double Dim netPay As Double Dim staff As New Employee staff.EmployeeNumber = 630485 staff.FirstName = "David" staff.LastName = "Salomons" staff.HourlySalary = 18.95 timeWorked = 44.5 netPay = staff.CalculateNetPay(timeWorked) txtEmployeeNumber = staff.EmployeeNumber txtFirstName = staff.FirstName txtLastName = staff.LastName txtHourlySalary = staff.HourlySalary txtTimeWorked = timeWorked txtNetPay = netPay Set staff = Nothing End Sub
Public ItemNumber As Long Public ItemName As String Public Size As String Public UnitPrice As Double Public Function CalculateDiscountAmount(ByVal DiscountRate As Double) As Double CalculateDiscountAmount = UnitPrice * DiscountRate / 100# End Function
Optional Arguments
As seen for regular procedures, a method can use one or more parameters that are optional. To specify that an argument is optional, when creating the method, type the Optional keyword to the left of the parameter and assign a default value to it. When calling the method, you can pass or ignore the argument.
The rules of optional arguments in methods are the same rules reviewed for regular procedures.
Practical Learning: Using Optional Parameters in a Method
Public ItemNumber As Long Public ItemName As String Public Size As String Public UnitPrice As Double Public Function CalculateDiscountAmount(Optional ByVal DiscountRate As Double = 20#) As Double CalculateDiscountAmount = UnitPrice * DiscountRate / 100# End Function
Private Sub cmdProcessStoreItems_Click() Dim item As New StoreItem Dim discount As Double, markedPrice As Double item.ItemNumber = 927497 item.ItemName = "Leaf Print Short Sleeve Shift Dress" item.Size = "Medium" item.UnitPrice = 59.5 discount = item.CalculateDiscountAmount() markedPrice = item.UnitPrice - discount txtItemNumber1 = item.ItemNumber txtItemName1 = item.ItemName txtItemSize1 = item.Size txtUnitPrice1 = item.UnitPrice txtDiscountRate1 = "Default" txtDiscountAmount1 = discount txtMarkedPrice1 = markedPrice item.ItemNumber = 480795 item.ItemName = "Small-Plaid Shirt" item.Size = "Large" item.UnitPrice = 34.95 discount = item.CalculateDiscountAmount(35) markedPrice = item.UnitPrice - discount txtItemNumber2 = item.ItemNumber txtItemName2 = item.ItemName txtItemSize2 = item.Size txtUnitPrice2 = item.UnitPrice txtDiscountRate2 = "35%" txtDiscountAmount2 = discount txtMarkedPrice2 = markedPrice Set item = Nothing End Sub
A Class as a Member Variable
A member variable of a class can be of the type of another class. To create the member, you ou can use your own class. Here is an example:
Public PayrollID As Long
Public Staff As Employee
Public Monday As Double
Public Tuesday As Double
Public Wednesday As Double
Public Thursday As Double
Public Friday As Double
Public Saturday As Double
Public Sunday As Double
You can also use one of the classes already available. After a member variable has been created as a class type of another class, it can be used Normally. Because the member is a class, declared as a reference, to use it, you must follow the rules of using an object. Foer example, you must make sure you have allocated memory for it.
Returning an Object From a Method
As done for a value of a regular type, you can create a method that returns an object. To do this, declare the method and specify the class as the return type.
Passing an Object as Argument
A class can be used as a parameter to a procedure or to a method of another class. When a class is passed as argument:
Constant Member Variables
You can make a member variable of class to be constant. To do this, type the Const keyword on the left side of the name of the variable and initialize it. Here is an example:
Const PI = 3.14159265359
Public Radius As Double
Built-In Classes and Objects
Introduction
To assist you in creating databases abd their objects, Microsoft Access and Microsoft Visual Basic ship with various objects and classes.
The most fundamental class in the VBA language is called Object. As a result, every object you will use in your application is primarily of type Object. Normally, if you want to use that class, you will first need to declare a variable of that class. Here is an example:
Dim objVariable As Object
You can then initialize the variable based on the actual class you want to use. To initialize the variable, use the Set operator.
After declaring a variable using the Object, you can access the members of the class it represents. When you use the Object class, the IntelliSense will not display the members of the class. This means that you must know the members of the actual class you are trying to use.
In some cases, if you don't know or may not need to specify the particular type of the object you want to use, you can declare the variable of type Object. The class you are trying to use must be one of the existing VBA classes and not one of the primitive data types.
To support databases, Microsoft Access provides a class named Database. This class allows you to get a rereference to the database you are using. To use it, declare a variable of this class. Here is an example:
Dim curDatabase As Database
A Windows control, or a control, is an object positioned on a form or report. To programmatically support controls, the Visual Basic language provides a class named Control.
An Access Object
There are various types of objects you will use in your databases. Each object belongs to a particular collection. Still, to generally identify these various objects, each is identified as an AccessObject. This means that the AccessObject object is used to identify an object that belongs to a collection, whatever that object is and whatever its parent collection is.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2002-2022, FunctionX, Inc. | Next |
|