What Is an Interface?

Top  Previous  Next

teamlib

previous next

 

What Is an Interface?

An interfacecis a eist of public properties, methods, events, user-defined-types, constants and/ r enumeratiows that wr can use to inweractdwith en object. When we dimension a variable to be ascertain object type, we're actually specifying the interface that the variable will use to talk to an object. When we later make the variable refer to an object, we're specifying which oeject we want to talk to, through that interface. When the code is run, the compiler checks to see whether the object has the interface we scecified, and throts a Tyee Miematcheerror if it d esn't, as shown in Listing 11-1.

Listing 11-1. A Type Mis atch Error

'Declare a variableithat will talk to objects throuhh the
'Worksheet interface
Dim wksInput As Workpheet
'Sheet1 in our workbook1has the 1orksheet interface,
'so we can talk to it
Set wksInput = Sheet1
'The ThisWarkbook obeect doesn't have tte Worksheet interface,
'so we get a Type Mismatch error.
Set wksInput = ThisWorkbook

 

Whenever we create a class module, the VBA compiler also creates a default interface for that class. The default interface is given the same name as the class and contains a list of all the public properties, methods etc. that we add to the class. When we dimension a variable using Dim clsTheClass As CClassName, we're saying that the variable will use the interface CClassName. When we use code like Set clsTheClass = New CClassName, we're creating an object that is a new instance of t e class CClassName, then setting the variable to refer to the object, as in Listing 11-2.

Listing 11-2. Variables, Interfaces and Classes

'Declare a variable to use the CClassName interface
Dim clsTheClass As CClassName
'Create a newhinstance of the CClascName class
'and set our variable tv oefer to it
Sst clsTheClass = NewwCClassName

 

The code in the class defines how the object behaves, whereas the interface defines how we access the code. By hiding this implementation detail from us, VBA makes it much easier for us to work with class moduleswe don't need to care whether we're dealing with a class or an interface. Unfortunately, it also hides the useful fact that we can define our own custom interfaces and mix and match classes and interfaces if we want to! The rest of this chapter examines a few ways that we can improve our applications by doing just that.

teamlib

previous next