Object Oriented Programming with Visual Basic
|Previous||Table of Contents||Next|
|Working with Strings in Visual Basic||Accessing Databases Using Visual Basic|
Visual Basic provides extensive support for developing object-oriented Windows applications. The subject area of object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. As such, a detailed overview of object oriented software development is beyond the scope of Visual Basic Essentials. Instead, we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to Visual Basic application development.
 What is an Object?
An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application.
Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.
 What is a Class?
Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be.
 Defining a Visual Basic Class
Before an object can be instantiated we first need to define the class 'blueprint' for the object. In this chapter we will create a Bank Account class to demonstrate the concepts of Visual Basic object oriented programming.
Begin by starting Visual Studio and creating a new Windows Application named vbObjects. Once the project opens, select the Project... menu and select Add class.... In the Add New Item dialog, name the new class file clsBankAccount.vb and click on the Add button.
Visual Studio will now add a new tab to code area for the new class file containing the following class declaration:
Public Class clsBankAccount End Class
We have now defined a class. The next step is to add some functionality to the class.
 Creating Visual Basic Class Properties
Class members or properties are essentially variables embedded into the class. Members can be Public or Private.
Public members can be accessed from outside the object. Private members can only be accessed by methods contained in the class. This is the key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters).
We can now extend our BankAccount class to add member variables to hold the account name and number. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as Private:
Public Class clsBankAccount Private strAccountNumber As String Private strAccountName As String Private intBalance As Integer Private accountFee As Integer = 5 End Class
Now that we have defined the properties of our class, the next task is to define methods that will give us access to our data.
 Defining Class Methods
Since we have declared our class data properties to be private, we need to provide methods which will give us access to those properties from our code. This is achieved using Get and Set methods. The syntax for get and Set methods is as follows:
Public Property propertyName() As datatype
.... Code to return property value
Set(ByVal value As datatype )
.... Code to return property value
To demonstrate this we will add to our class to provide methods to get and set the account number and name. Note that after you type in the Public Property line of the declaration, Visual Studio automatically creates a template for the Get and Set methods, which should be filled in as follows:
Public Class clsBankAccount Private strAccountNumber As String Private strAccountName As String Private intBalance As Integer Private accountFee As Integer = 5 Public Property AccountName() As String Get End Get Set(ByVal value As String) End Set End Property Public Property Balance() As Integer Get Return intBalance End Get Set(ByVal value As Integer) intBalance = value End Set End Property End Class
Now that we have defined our getter and setter methods we can add our own method to perform a task. This is the same as writing a Visual Basic function. The purpose of our method will be to subtract the account fee from the current balance:
Public Function subtractFee() As Integer intBalance = intBalance - intAccountFee Return intBalance End Function
When called, the above function subtracts the account fee from the balance, assigns the new balance to the intBalance variable and returns the new total.
Now that we have added some functionality to our class it is time to instantiate objects from this class blueprint.
 Instantiating an Object from a Visual Basic Class
The process of creating an object from the class 'blueprint' is called instantiation. Essentially, you instantiate an instance of the class and give that instance a name by which you will refer to it when accessing members and calling methods. You can create as many object instances of a class as you desire. Objects are instantiated from a class using the new keyword. Visual Basic provides two ways to instantiate an object from a class. These two alternatives are known as late-binding and early binding.
Late binding occurs when the assignment of the object to the variable occurs at run-time when execution reaches the code where the object is created. There are drawbacks to this approach in that any syntax checking is not performed until the application runs because the compiler has no way of checking whether you are referencing valid class members, resulting in potential run-time exceptions. Another disadvantage is that execution can be slowed when using late-binding since much of the work performed by the compiler when using early binding has to be performed at runtime.
Late binding is achieved using the new keyword as follows:
Dim objBankAccount As Object objBankAccount = New clsBankAccount()
Early binding, on the other hand, has none of the draw backs of late-binding. The compiler performs syntax checks to ensure the object is being used correctly and execution speed is increased because the binding takes place at compile time - not at run-time.
Early binding is performed as follows:
Dim objBankAccount As clsBankAccount objBankAccount = New clsBankAccount
It is also possible to instantiate the object at the same time that it is declared:
Dim objBankAccount As New clsBankAccount()
 Accessing Object Properties and Methods
Now that we know how to write a class and instantiate objects from the class, we now need to know how to call the methods we created in the class. First, you will recall that we created Get and Set functions the data members of our class. Because we did this, we can change and access these properties simply by referencing them as we would any other property. For example:
Dim objBankAccount As New clsBankAccount() objBankAccount.AccountName = "John Smith" objBankAccount.Balance = 1230 MessageBox.Show(objBankAccount.AccountName & " has a balance of " & CStr(objBankAccount.Balance))
The above code excerpt assigns values to the AccountName and account balance properties of our object. It then references the properties in order to display a string which reads "John Smith has balance of 1230" in a MessageBox.
We can also call our subtractFee() method as follows:
Dim objBankAccount As New clsBankAccount() Dim intNewbalance As Integer objBankAccount.AccountName = "John Smith" objBankAccount.Balance = 1230 intNewbalance = objBankAccount.subtractFee() MessageBox.Show(objBankAccount.AccountName & " has a balance of " & CStr(objBankAccount.Balance))
The result will be a message which reads "John Smith has balance of 1225", since the account fee has now been subtracted from the balance.
|Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for only $9.99|