Objects and classes in Visual Basic
-
Upload
sangeetha-sg -
Category
Technology
-
view
415 -
download
1
Transcript of Objects and classes in Visual Basic
An object is a combination of code and data that can be treated as a unit.
• An object can be a piece of an application, like a control or a Form.
• The entire application can also be an object.
A class is usually described as the templatefrom which an instance, i.e. an object can be created.
• Each object in Visual Basic is defined by a class.• For example, an individual Form is an instance of
the Forms class.
Encapsulation• A key rule in encapsulation is that programs
should not access the instance variables in the object directly.
• Interaction of programs with this data is possible only through the object’s properties and methods.
• Visual Basic fully supports encapsulation.
InheritanceInheritance, the ability to make classes descend
from other classes is not supported by Visual Basic.
Polymorphism
• A class that inherited its data structures and routines from another class is called polymorphism.
• Polymorphism is helpful when creating new objects from old ones.
• When a new object is defined that is related to an existing object, it is not necessary to rebuild any of the existing code in order to take the new object into account.
Object Variables
Object type variables are used for working with objects.
For example, when using the Me keyword to refer to the current object, we are using an object variable.
The scope of an object variable is given with Dim, Private, Public, Static, etc. Thus we can have local, form-level, or public (global) object variables. Some examples are discussed here.
Dim frmvar As Form
Private optnew As Optionbutton
The Set command is mainly used to simplify lengthy control references.
For example, we assign Set Fun= frmhelp.texthelp, it can be written as Fun.forecolor instead of frmhelp.texthelp.forecolor
The New keyword is used only when we want Visual Basic to create a new instance of the original object.
Dim frmform As New Form1
Example:
Dim frmAform as New Form1
Dim frmBform as New Form1
frmAform.Show
frmBform.Show
frmAForm.Move Left – 199, Top + 100
frmBForm.Move Left – 399, Top + 200
The above example shows two copies of the original Form, Form 1. The locations are determined by the value of Left and Top properties of the original Form.
Working with Objects
Visual Basic supports properties, methods and events.
• In Visual Basic, the setting or attributes of an object are referred to as properties
• The various procedures that can operate on the object are called its methods.
• Events are triggered when some aspect of the object is changed.
Controlling Objects with their PropertiesThe individual properties of the objects can vary.
Some properties can be set at design time. We can use the Properties window to set the value of these properties without writing any code.
Some properties are not available at design time; these properties are manipulated at run time using the code.
• Properties that we can set and those that we manipulate at run time are called read-write properties
e.g. text properties of a text box.
• Properties that we can only read at run time are called read-only properties
e.g. name property of a control.
Setting properties values:
The value of a property should be set when it is required to change the appearance or behaviour of the object value of a property.
For Eg: The Text property of a text box can be changed in order to change the contents of the text box.
The following syntax is used to set the value of a property.
object.property = expression
Getting properties values:
We get the value of a property when we want to find the state of an object before our code performs additional actions(such as assigning the value to another object)
For Eg: To get the value of a property, we use the following syntax,
variable=object.property
Performing actions with methods:
Methods can affect the value of properties. In Visual Basic, list boxes have a List property, which can be changed using the Clear andAddItem methods.
Using methods in code:When we use a method in code, the manner in which
we write the statement depends on the number of arguments the method requires and whether the method returns a value. When a method does not take arguments, we write the code using the following syntax :
object.method
In this example, the Refresh method repaints the picture box
Picture1.Refresh 'Forces a repaint of the control.Some methods, such as Refresh method, do not have arguments and do not return values.
If the method takes more than one argument, we separate the argument with a comma.
For example, the Circle method uses arguments specifying the location, radius and color of a circle on a form. To Draw a blue circle with a 1200-twip radius. We use the following syntax
Form1.Circle(1600, 1800),1200,vbBlue
If we consider the return value of a method, we must enclose the arguments in parenthesis.
For example, the GetData method returns a picture from the Clipboard. We use the following syntax
Picture= Clipboard.GetDta(vbCFBitmap)
If there is no return value, the arguments appear without parentheses.
For example, the AddItem method does not return a value. List1.AddItem "yourname" 'Adds the text
'yourname' to a list
Specific and Generic Object typesA specific Form variable can refer to only one Form in the
application (though it can refer to one of the many instances of that Form).
Similarly, a specific control variable can refer to only one particular type of control in our application, such as TextBox and ListBox.
A Generic object variable can refer to one of many specific types of objects.
A generic Form variable, for example can refer to any Form in an application; a generic control variable can refer to any control on any form in an application.
Generic object variables are useful when we do not know the specific type of object a variable will refer to at run time. It is ideal to use a generic Form variable when the code is to operate on any Form in the application.
Example for specific object type
Place a TextBox on a Form and Add the following code
Private Sub Form_Click()
Dim anyText As TextBox
Set anyText=Text1
anyText.Text=“Hello”
End Sub
Now the Text property of the text box will be changed to Hello
Example for generic object type
Place Frame, Label and CommandButton controls on a
Form in any order and Add the following code.
private Sub Form_Click()
Dim anyControl As Control
Set anyControl=Form1.Controls(3).
anyControl.Caption=“Hai! Good Morning”
End Sub
Now the caption of the control we placed third in sequence on the Form will change to “Hai! Good Morning”
Forms as Objects
• Forms are used to make up the interface of an application.
• They are also objects that can be called by other modules in the application.
• They are closely related to class modules.
• Major difference between the two is that Forms can be visible objects, whereas class modules have no visible interface.
Constructors and Destructors
When we use the New operator to create an object, Visual Basic automatically allocates the space it needs for our object’s data members.
We can write any other initialization code in the constructor if we need to.
Assigning default properties and asking the user for additional data are the operations of constructor
The role of destructors is to free the space allocated for the constructor. VB automatically de-allocates the space once the object is destroyed.
An object is destroyed when the last reference to that object goes out of scope.
Collections When related objects are grouped in Visual Basic, a
collection is created.
They are sometimes created automatically when Forms or controls are added to an application.
Eg: When the Form is loaded, it is automatically added to the Forms collection.
A custom control can also have a collection of elements.
Eg: A TreeView control is a custom control having Node objects, the node objects in a TreeView control form a collection.
If controls are added to an application either in design time or runtime in a control array, they form a control collection.
Collection ObjectA collection object is an ordered set of items that can be
considered as a unit.
The items in the Collection can be of any data type, hence by default the type of the item is Variant.
The properties and methods of Collection objects are given in table:
METHOD DESCRIPTION
Add Add items to the collection
Remove Remove items from the collection
Count Returns the number of items present in
the collection
Item Returns an item referenced by index
property
For….Each StatementThe implementation of ‘For Each….Next’ statement is a
way of enumerating a collection. This object uses an object called an enumerator. An enumerator keeps track of the place where we are present in the collection and returns the next item when it is needed.
Private Sub Form_Load
Dim NewControl As Variant
For Each NewControl In controls
If TypeOf NewControl Is CommandButton then
NewControl.Enabled=True
EndIf
Next
EndSub
Controls Collection
• Controls collection is an array that contains all the controls on a form in Visual Basic.
• The Count property of the Controls collection returns the number of controls on the Form.
• The salient feature of Controls collection is to perform an action on a group of controls.
Classes and Class ModulesClasses are built by adding custom properties to a
Form and then used as templates for new objects.
Class module object contains the code for the custom properties(via property procedure) and methods that object define.
Creating a New Class Module:
A new class module is created at design time by choosing Project Add Class Module.
Each class module can respond to only two events: Initialize and Terminate. They are triggered when an instance of class created or terminated.
Steps for Creating a Class Module
A new standared.EXE project is opened.
A class module is added to the new project by selecting Add Class Module from the Project Menu.
Four CommandButton controls are drawn on the Form.
Table lists the property values we need to set for the objects in this example,
Object Properties Settings
Class module Name Thing
Command1 Caption Show the Thing
Command2 Caption Reverse the Thing’s Name
Command3 Caption Create New Thing
Command4 Caption Temporary Thing
Coding included in the Code Window of the Class Module
Option Explicit
Public Name As String
Private mdtmCreated As Date
The mdtmCreated - used to store the value of read-only Created property.
The created property returns the date and time a Thing object was created.
To implement Created property, add Property Get to the declarations section of the class moduleProperty Get Created() As Date
Created=mdtmCreated
End Property
The Thing object has one method, ReverseName, which simply reverses the order of the letters in the Name property.
Public Sub ReverseName()
Dim intCt As Integer
Dim strNew As String
For intCt=1 To Len(strNew)
strNew=Mid$ (strNew, intCt, 1) & strNew
Next
Name=strNew
End Sub
Class modules have two events; Initialize and Terminate.
In the Object drop down of the class module, select Class.
The procedure drop down will display the events
Place the following code in event procedures,
Private Sub Class_Initialize()
mdtmCreated = Now ‘ Display object properties.
MsgBox “Name: “ & Name & “Created, ,”Thing Initialize”
End Sub
Private Sub Class_Terminate() ‘ Display object properties
MsgBox “Name: “ & Name & VbCrLf & “Created, , “Thing Terminate”
End Sub
• The Initialize event procedure contains code that needs to be executed at the moment the object is created, such as providing the time stamp for the Created property.
• The Terminate event contains any code that is needed to execute in order to clean up after the object when it is being destroyed.
Using the Thing Object:
The following syntax is added to the declarations section of the Form
Option Explicit
Private mth As Thing
The variable mth - hold a reference to a Thing object, which will be created in the Form’s Load event.
The code in the Form_Load event procedure, and in the Click event procedures for the four buttons is given below.
Private Sub Form_Load()
Set mth = New Thing
mth.Name = InputBox(“Enter a name for the Thing”)
End Sub
Private Sub Command1_Click()
MsgBox “Name:” & mth.Name & vbCrlf & “Created:” & mth.Created, , “Form Thing”
End Sub
vbCrlf – used to display the created date and time in next line.
Private Sub Command2_Click()
mth.ReverseName
Command1.Value = True
End Sub
Private Sub Command3_Click()
Set mth = New Thing
mth.Name = InputBox(“ Enter a name for the new Thing”)
End Sub
Private Sub Command4_Click()
Dim thTemp As New Thing
thTemp.Name = InputBox(Enter a name for the Temporary Thing”)
End Sub
Running the Project:
Press the key F5 to run the project.
In the code of the Form_Load event procedure, the New operator is used to create a Thing object.
A reference to this Thing is assigned to the variable mth.
An InputBox will be displayed asking for a name for the Thin.
A name is typed and Enter Key is pressed.
This name is accepted as the return value and is assigned to the Name property of the Thing object.
Show the Form Thing:
We can verify if the Name property has been assigned by pressing the first button, “Show the Thing,” which displays a message box with all the properties of the Thing object.
Reverse the Thing’s Name
Press the second button, Reverse the Thing’s Name . This button calls the ReverseName method to turn the Thing’s object’s name around and then clicks the first button to display the updated property values.
Create New Thing :• Click the Create New Thing button to destroy the
existing Thing object and create a new one.• The new operator causes a new Thing to be created,
hence we would see the MsgBox displayed by the new Thing’s Initialize event.
• When we click OK, a reference to the new Thing is placed in the form-level variable mth.
• This wipes out the reference to the old Thing. As there are no more references to it, it is destroyed and this is seen in its Terminate event message box.
• When the Ok button is clicked, the InputBox statement requests a name for the new Thing.
• To destroy the old Thing before creating new one, addSet mth = Nothing at the beginning of the event
procedure.
Temporary Thing :
When the variable thTemp was declared As New, a Thing object will be created the moment one of its properties or methods is invoked.
This will happen when the return value of the InputBox is assigned to the Name property. Type a name and click OK on the InputBox.
Now the Thing Initialize message box indicates that the Name property is still blank.
When we click OK to dismiss the message box, the value from the InputBox statement is finally assigned to the Name property.
With this, the Click event procedure ends, and the variable thTemp goes out of scope.
The object reference for the temporary Thing is released, and we would view Thing Terminate message box.
Closing the program:
The program is closed by clicking the Close button.
When the program closes , Form1 is destroyed.
The variable mth goes out of scope, there are no remaining references to the Thing, so it’s destroyed and its Terminate event message box is displayed.
Ending the program with End button, or with an End statement in our code, halts the program immediately, without executing the Terminate events of any objects.