Author: Chris Eastwood
Author’s WebSite: http://www.vbcodelibrary.com
This is the first in a series of Object Oriented Programming (OOP) tutorials using Visual Basic. This first part introduces you to the concepts behind OOP and explains objects as they are used in Visual Basic.
Definition of an Object
It seems that there is no one definition of an object that developers and designers can agree on. Possibly the one that is nearest to the mark is :
“An object is an entity able to save a state (information) and which offers a number of operations (behaviour) to either examine or affect this state”
(From Jacobson: Object Orientated Software Engineering)
That’s all very well, but what does that mean to a VB Programmer ? If you’ve ever written a Visual Basic program with a form or controls, then you’ve already had a quick taste of objects. Consider a Visual Basic Form – a form is an object that VB knows about. Once a form is running in your program, it is able to :
- Save a State (eg. Height, Width, Caption etc)
- Offer a number of operations (eg. Show, Hide, etc)
An object is supposed to offer a programmer or another program, an Application Programming Interface (API). For an object, this consists of :
- Properties – the ability to set and get ‘state’ values referenced by the object (eg. Form1.Height etc)
- Methods – the routines available from the object that allow some kind of processing to take place within the object (eg. Form1.Show, Form1.Hide etc)
Definition of a Class Module
A class module is simply a description or a ‘blueprint’ of an Object. For example :
- My telephone call to my mechanic on 20th February 2000
- My telephone call to a scrapyard on 21st February 2000
– These could both be called Instances of the class Telephone Call.
An object is an instance of a class – whereas a class is a type of which there maybe many instances of objects
Thinking about objects
Let’s consider how we can perceive a real-world object.
When I get into my car in the morning to drive to work, I place my key in the ignition to start the engine and (hopefully) drive to work carefree. I don’t need to know about the internal combustion engine to drive my car, nor do I need to understand how the wiring works in order to operate my lights and indicators. The car can be said to provide an Interface that I need to know about (and a separate interface for those brave enough to look under the bonnet). My car can be though of as an object that offers properties (current speed, fuel level, oil level etc) and methods (start-engine, stop engine etc).
Signs of a ‘good’ Object
A class representing an object should :
- Provide a well-defined API – this should provide external software / programmers with the ability to perform valid operations with the object.
- Be as complete as possible – the programmer shouldn’t have to call external routines in order to ‘do something’ with the object
- Be Robust – a class should reject illegal or incorrect input. For instance, my ‘car’ object shouldn’t allow me to try and change into sixth gear, nor should it allow me to us the ‘driving’ method before the ‘start-engine’ method has been called
Real World VB Object Programming
Now that you have a better understanding of the concepts behind Object Orientated Programming, let’s move onto a Visual Basic example. Since VB4, developers have been able to add class modules to their projects. While a lot of people assume that just adding a class to your program makes it Object Orientated, the program is doomed to failure unless there is a good design for the system.
A good design comes from a good understanding of the problem / project domain – you need to fully understand :
- What are the objects in the system
- What are the relationships between the objects
- What are the interactions between the objects
For our VB example, we’ll take a ‘Bank Account’ real world object and create a Visual Basic class that models it’s real-world behaviour.
When we think about a Bank Account, we think of it as having :
- A Balance
- An Interest Rate
- A monthly Fee
- A customer
- The ability to accept a deposit of funds
- The ability to allow a withdrawl of funds
- The ability to calculate interest
Hopefully, you’ll have read through the above list and already identified what are the properties and methods of the class module we are about to create. Let’s jump straight into the Visual Basic IDE and start creating our project.
Create a standard VB EXE project, call it prjBankAccount1. Next, add a class module to the project and call it cBankAccount.
The cBankAccount class is listed below – notice how when the 'cBankAccount' object is instantiated (ie. Set o = New cBankAccount), the class uses it’s own internal properties to set the internal varables. This ensures that errors are caught right from the start.
option Explicit ' ' Bank Account Class ' private mdblBalance as Double private mdblInterestRate as Double private mdblMonthlyFee as Double ' private Sub Class_Initialize() ' ' Class Initialize is the first routine ' called when you create a 'cBankAccount' ' object. ' ' Eg. set oBA = new cBankAccount ' mdblBalance = 0 me.InterestRate = 1.75 me.MonthlyFee = 5 ' End Sub ' private Sub Class_Terminate() ' ' Class_Terminate is called when you ' set the object to nothing (or it falls out of scope) ' End Sub ' public property get Balance() as Double ' ' Return the Balance of this account ' Balance = mdblBalance ' End property ' public property get InterestRate() as Double ' ' Return the interest rate ' InterestRate = mdblInterestRate ' End property ' public property let InterestRate(byval dblNewInterestRate as Double) ' ' Check for invalid interest rates ' If dblNewInterestRate < 0 then Err.Raise vbObjectError + 2001, _ "cBankAccount::InterestRate", _ "Invalid Interest Rate set : " & dblNewInterestRate End If ' ' Now set the rate ' mdblInterestRate = dblNewInterestRate End property ' public property let MonthlyFee(byval dblNewFee as Double) ' ' Check for invalid Fee ' If dblNewFee < 0 then Err.Raise vbObjectError + 2003, _ "cBankAccount::MonthlyFee", _ "Invalid Fee Amount : " & dblNewFee End If ' mdblMonthlyFee = dblNewFee ' End property ' public Sub MonthlyProcessing() ' ' This routine takes the monthly fee ' from the account, then updates the ' balance with interest earned. ' CalcFee CalcInterest ' End Sub ' public Sub Withdraw(byval dblAmount as Double) ' ' Withdraw some money from the account ' ' Sanity check first ! ' If dblAmount <= 0 then Err.Raise vbObjectError + 2002, _ "cBankAccount::Withdraw", _ "Invalid Withdraw amount : " & dblAmount End If If (mdblBalance - dblAmount) < 0 then Err.Raise vbObjectError + 2003, _ "cBankAccount::Withdraw", "Insufficient Funds" End If mdblBalance = mdblBalance - dblAmount End Sub ' public Sub Deposit(byval dblAmount as Double) ' ' Deposit some money to the account ' ' Sanity check first ' If dblAmount <= 0 then Err.Raise vbObjectError + 2002, _ "cBankAccount::Deposit", _ "Invalid deposit amount : " & dblAmount End If ' mdblBalance = mdblBalance + dblAmount ' End Sub ' private Sub CalcFee() ' ' This routine removes the monthly fee ' from the balance ' mdblBalance = mdblBalance - mdblMonthlyFee ' End Sub ' private Sub CalcInterest() ' ' This is private, as we don't want ' other programs / programmers updating ' the balance except through the ' proper interfaces ' ' The calculation updates the balance with the monthly interest ' due ' mdblBalance = mdblBalance + _ (mdblBalance * (mdblInterestRate / 120)) ' End Sub ' '
The class module will be expanded upon in the next part of this tutorial when we’ll cover another object orientated concept – polymorphism.