What Is an Interface?An interface is a list of public properties, methods, events, user-defined-types, constants and/or enumerations that we can use to interact with an object. When we dimension a variable to be a certain 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 object 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 specified, and throws a Type Mismatch error if it doesn't, as shown in Listing 11-1. Listing 11-1. A Type Mismatch ErrorWhenever 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 the class CClassName, then setting the variable to refer to the object, as in Listing 11-2. Listing 11-2. Variables, Interfaces and ClassesThe 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. |