Creating Class Methods

In Chapter 4, we were introduced to the concept of subs and functions. Class modules have them as well, but just to give the impression that they're somewhat special, we refer to them as methods. It makes some sense when you consider that a class's procedures carry out actions on its properties and therefore constitute the method by which those actions are executed.

In the same way that methods are executed against objects in the Access object model, class methods are executed against class objects. For example, when we want to move a DAO recordset cursor to the next record, we are actually using method exposed by the Recordset object.


There are three types of method: sub(program)s, functions, and properties. Subs and functions you know about, but properties, which I will introduce a little later, are a special type of method that can exhibit the characteristics of both.

To create an external interface for our class, we need to add subs, functions, and properties. Let's take a closer look at our friend, the Kennel class.

Option Compare Database

Option Explicit

Private mintDogs As Integer

Public Sub AddDogs(intHowMany As Integer)

mintDogs = mintDogs + intHowMany End Sub

Public Function FeedDogs() As Boolean

'Code to implement the FeedDog action. If DogsNeedFood() = True Then 'code to feed the dogs. FeedDogs = True End If End Function

Private Function DogsNeedFood() As Boolean

'Code to determine if the dogs are hungry. 'For our example, we'll just return True. DogsNeedFood = True End Function

Public Property Let Dogs(intNewValue As Integer)

mintDogs = intNewValue End Property

Public Property Get Dogs() As Integer

Dogs = mintDogs End Property

In this class module, we have a private integer variable called mintDogs, declared at module level, so all our procedures can access it. We also have a public subprocedure called AddDogs, a public function called FeedDogs(), a private function called DogsNeedFood(), and two property procedures, both called Dogs, which we'll explain later.

The AddDogs method takes a single integer argument that specifies the number of dogs to add to our kennel. Nothing special there! The FeedDogs method takes no arguments, but returns a Boolean value indicating success or failure. You might also notice that FeedDogs executes some code to actually feed the animals, but only if the DogsNeedsFood() function returns True. Once the dogs have had their dinner, FeedDogs returns True to the code that called it and everybody's happy.

Now, you've probably already noticed that we seem to have duplicate procedure names. We do, but property procedures are a special type of procedure for which duplicate names are allowed. But before we discuss property procedures, it's appropriate to first explain a term that is often used to describe the object properties and methods that are visible and accessible to the VBA code that instantiated the object—the interface.

0 0

Post a comment