Members
Technology Zones
IBM Learning Center
Articles
Hosted By
Info
|
Rated
Read 94,956 times
Contents
Related Categories
Introduction to Class Programming - Building Your First Class
Building Your First Class
Creating a class in Visual Basic is very simple: just select the Add Class
Module command from the Project menu. A new code editor window appears on an
empty listing. Visual Basic automatically add a class module named Class1, so the very
first thing you should do is change the Class name in the Project Properties
window in a more appropriate name. The first
version of our class includes only a few properties. These properties are
exposed as Public members of the class module itself.
- Start Visual Basic.
- In the New Project
dialog box, select Standard EXE, then click OK.
- On the Project menu, click
Add Class Module.
- In the Add Class Module dialog box, select Class Module,
then click Open.
- In the Properties window, set the Name property for the
class module to Student.
-
To create public property
- In the Code window, type the following:
'In the declaration section of the Student class module
Public Student_ID As String
Public FirstName As String
Public LastName As String
Public MajorCode As String
Public YearLevel As String
Public BirthDate As Date
This is a very simple class, which consists of Public properties, so
we are not distracted by OOP details (not yet), we will just examine the
concept. Once you've created a
class, you can create an instance of that class then you can use the properties
of that class. The following example creates an instance of the Student class,
and sets and retrieves its properties:
- Place a
command button on Form1.
- In the Click event for the command button, type the
following:
'Declare an object Student
Dim objStudent As Student
'Create an instance of the class
Set objStudent = New Student
'Use the object Student
objStudent.StudentID = "12345"
objStudent.FirstName = "Cathrina"
objStudent.LastName = "Aniversario"
objStudent.MajorCode = "C"
objStudent.YearLevel = "Freshmen"
objStudent.BirthDate = "Oct 10, 1980"
MsgBox "Student ID : " & objStudent.StudentID & vbCrLf & _
"Student Name : " & objStudent.FirstName & " " & _
objStudent.LastName & vbCrLf & _
"Major Code : " & objStudent.MajorCode & vbCrLf & _
"Year : " & objStudent.YearLevel & vbCrLf & _
"BirthDate : " & objStudent.BirthDate
Set objStudent = Nothing
|
- On the Run menu
in Visual Basic, click Start.
- When the program is running, click the Command1
button.
- Click OK to close the message box.
- On the Run menu in Visual
Basic, click Stop.
Object Keyword
The New keyword
The New keyword (when used in a Set command) tells Visual
Basic to create a brand-new instance of a given class. The keyword then
returns the address of the instance data area just allocated.
The Setcommand
The Set command simply copies what it finds to the right of the
equal sign into the object variable that appears to the left of it. This value
can be, for example, the result of a New keyword, the contents of
another variable that already exists, or the result of an expression that
evaluates to an object. The only other tasks that the Set command
performs are incrementing the reference counter of the corresponding instance
data area and decrementing the reference counter of the object originally
pointed to by the left-hand variable (if the variable didn't contain the
Nothing value):
|
Unlike regular variable, which can be used as soon as they have been
declared, an object variable must be explicitly assigned an object reference before you
can invoke the object's properties and methods. When an object variable has not been
assigned, it contains the special Nothing value, meaning it doesn't contain any
valid reference to an actual object. For example try this code:
' Declare the variable
Dim objStudent As Student
' Then comment out the next line
' Set objStudent = New Student
' Raises an error 91
' "Object variable or With block variable not set"
MsgBox objStudent.FirstName
|
The code will give you an error, because we trying to use an object that
doesn't exist. This behavior is favorable because it doesn't make much sense to use a
property of an object that doesn't exist. One way to avoid the error is to test
its contents of an object variable using the Is Nothing
' Use the variable only if it contains a valid object reference
If Not (objStudent Is Nothing) Then MsgBox objStudent.FirstName
MsgBox objStudent.FirstName
|
But in other cases, you may want to create an object and then assign its
properties. You might find it useful to declare an auto-instancing object
variable using the As New clause:
Dim objStudent As New Student ' Auto-instancing variable
|
At runtime, when Visual Basic encounters a reference to an auto-instancing
variable, it first determines whether it's pointing to an existing object and
creates a brand new instance of the class if necessary. But auto-instancing
variables have an advantage and disadvantage:
- It reduce the amount of code you need to write to be up and running with
your classes. This can be useful if you are prototyping an application.
- In
some condition, you might declare a variable but never actually use it: which
happens all the time with standard variables and with object variables too. In
truth is, if you create an object with a Set command at the beginning of a
procedure, you might be creating an object for no real purpose (thus taking both
time and memory). On the other hand, if you delay the creation of an object
until you actually need it, you could soon find yourself drowning in a sea of
Set commands, each preceded by an Is Nothing test to avoid re-creating an object
instanced previously. Auto-instancing variables are automatically created by
Visual Basic only if and when they are referenced. This is probably the
situation in which auto-instancing variables are most useful.
- Your object variable cannot be tested against the Nothing value. In fact,
as soon as you use one in the Is Nothing test, Visual Basic insistently creates
a new instance and the test always returns False
- It eliminate errors, which is sometimes this is specifically what you don't
need especially during the development stage, because during this state, you want to see
all the errors
because this might be the symptoms of other serious deficiency in your code logic.
- Auto-instancing variables make the debugging step a little more difficult
to understand because you can never be sure when and why an object was created.
- You can't declare an auto-instancing variable of a generic type, such as Object, or
Form because Visual Basic must know in advance which kind of object
should be created when it references that variable for the first time.
- Finally, each time Visual Basic references an auto-instancing variable, it
incurs a small performance hit each time Visual Basic reference an
auto-instancing, because Visual Basic has to check whether it's Nothing.
In short, auto-instancing variables are not the best choice for creating the
object and you should stay away from it.
Object Keyword
The Nothing value
The Nothing keyword is the Visual Basic way of saying Null
or 0 to an object variable.
The Is operator
The Is operator is used by Visual Basic to check whether two
object variables are pointing to the same instance data block. At a lower
level, Visual Basic does nothing but compare the actual addresses contained
in the two operands and return True if they match. The only possible variant
is when you use the Is Nothing test, in which case Visual Basic
compares the contents of a variable with the value 0. You need this special
operator because the standard equal symbol, which has a completely different
meaning, would fire the evaluation of the objects' default properties:
|
Properties Of a Class
Now is the time to make our class to more
robust class. A robust class is one that actively protects its internal data
from tampering. So how can a class protect itself from invalid assignments, such
as an empty string for its FirstName or LastName properties. To accomplish
this purpose, you must change the internal implementation of the class module, because in
its present form you have no means of trapping the assignment operation. Simply
change all the Public member into Private members and encapsulate them in pairs
of Property procedures.
-
To change our Student class
- Double click the class Student.cls in the
Project Explorer
- In the Student Class Module, change all word Public to
Private and add
a prefix m_ in front of all private variables, as shown below:
'In the declaration section of the Student class module
Private m_Student_ID As String
Private m_FirstName As String
Private m_LastName As String
Private m_YearLevel As String
Private m_BirthDate As Date
|
NOTE
You can also use Replace Dialog box. To do this, press Ctrl-H,
the Replace
Dialog box appears. On the Find What combo box, type Public. Next on the
Replace
With combo box, type Private, then click Replace All button.
Appending the prefix m_ is just a personal style, this way it
keeps my property name and private member variable synchronize and it is
commonly used in programming. Feel free to use it or to create your own
style.
- In the Student
Class Module, type the following code:
'In the declaration section of the Student class module
Private m_Student_ID As String
Private m_FirstName As String
Private m_LastName As String
Private m_MajorCode As String
Private m_YearLevel As String
Private m_BirthDate As Date
Property Get MajorCode() As String
MajorCode = m_MajorCode
End Property
Property Let MajorCode(ByVal strNewValue As String)
' Raise an error if an invalid assignment is attempted.
If Len(strNewValue) = 0 Or Len(strNewValue) > 1 Then Err.Raise 5
m_MajorCode = strNewValue
End Property
Property Get FirstName() As String
FirstName = m_FirstName
End Property
Property Let FirstName(ByVal strNewValue As String)
' Raise an error if an invalid assignment is attempted.
If Len(strNewValue) = 0 Then Err.Raise 5 ' Invalid procedure argument
' Else store in the Private member variable.
m_FirstName = strNewValue
End Property
Property Get LastName() As String
LastName = m_LastName
End Property
Property Let LastName(ByVal strNewValue As String)
' Raise an error if an invalid assignment is attempted.
If Len(strNewValue) = 0 Then Err.Raise 5 ' Invalid procedure argument
' Else store in the Private member variable.
m_LastName = strNewValue
End Property
Property Get StudentID() As String
StudentID = m_Student_ID
End Property
Property Let StudentID(ByVal strNewValue As String)
' Raise an error if an invalid assignment is attempted.
If Len(strNewValue) = 0 Then Err.Raise 5 ' Invalid procedure argument
' Else store in the Private member variable.
m_Student_ID = strNewValue
End Property
Property Get BirthDate() As Date
BirthDate = m_BirthDate
End Property
Property Let BirthDate(ByVal datNewValue As Date)
If datNewValue >= Now Then Err.Raise 1001, , "Future Date!"
m_BirthDate = datNewValue
End Property
Property Get YearLevel() As String
YearLevel = m_YearLevel
End Property
Property Let YearLevel(ByVal strNewValue As String)
Dim varTemp As Variant
Dim found As Boolean
For Each varTemp In Array("Freshmen", "Sophomore", "Junior", "Senior")
If InStr(1, strNewValue, varTemp, vbTextCompare) Then
found = True
Exit For
End If
Next
If Not found Then Err.Raise 5
m_YearLevel = strNewValue
End Property
|
NOTE
Visual Basic can help you in typing Property Procedure by Add
Procedure command from the Tools menu, which creates a
templates for Property Get and Let procedures. But you
should edit the result to a proper data type, because all properties
created by this command is of type Variant.
- On the Run menu
in Visual Basic, click Start.
- When the program is running, click the Command1
button.
- Click OK to close the message box.
- On the Run menu in Visual
Basic, click Stop.
Everything works as before. What we have done, is make the class a bit more
robust because it now refuses to assign invalid values to its properties. To see
what I mean, just try to issue this command:
objStudent.FirstName = "" 'Raises an error 'Invalid Procedure call
|
Comments
-
Posted by mailforanu on 07 Jun 2008
[quote user="Developer Fusion Bot"]
This thread is for discussions of Introduction to Class Programming.
[/quote]
This... -
Posted by jbhavani on 12 Jul 2007
Hello Sir,
I have just seen u'r examples for class module.u'r explaination is simply superb!!!!
now i clearly understood the class module concept in VB.
Thank... -
Posted by CraigaNelson on 15 May 2007
This was a very good fundamental article on the use of classes in VB. looking forward to additional more advance content -
Posted by davulcu on 16 May 2006
It s a great sample about the class programming. However, it s still uncertain for me where I can use this in real life.
Can anyone give me an example ?
Posted by kirov on 05 Oct 2005
what kind of help you wants from me. i mean to clear out your visual basic basics by giving you some tutorials or anything else. bye
|
Search
Related Content
Code Samples
New Members
|