Understanding properties,
methods, and events
All classes include some comment elements. Because a class is essentially
a black box that accepts input and provides output, you need some way
to interact with it. Classes provide three common constructions that help
you interact with them: properties, methods, and events. The following list
describes each of these constructions.
Properties:
A property provides a means to access data within the
object. Unlike a variable, a property can include code that controls
the interaction with the object data. The property might check the data
type of the incoming request or format the outgoing data in some way.
Properties can provide read/write access so that you can change the
object data as well as use it in your own code. However, a class devel-
oper can also choose to make a property read-only or write-only.
Methods:
A method provides a means of asking the object to perform
a task. As with a
Function
or
Sub
, a method can return a value and
accept data as input. Unlike with a
Function
or
Sub
, you need not
worry about the inner workings of the method. Your only concern is
that you must provide certain input to obtain specific output. In some
cases, you will find methods that accept no input and provide no output
but still perform a task. For example, a
Refresh()
method may tell the
object to refresh its data. Methods always perform a task, but need not
work with data (from an external perspective) to do it.
Events:
An event is the object’s way of interacting with the outside world.
An event signals that something has happened. A user might have clicked
a button, or the status of a text box might have changed. The events that
an object signals depend on the communication that the class designer
chooses to provide. Even when an object signals an event, however, noth-
ing takes place in your code unless you create an event handler, a special
Sub
or
Function
, to do something with the event.
Defining classes
You might want to think of a class as a substitute for a
Function
or a
Sub
, but
classes are separate. A
Function
or
Sub
always describes a
procedure
— a
list of steps. A
class
describes a thing. You can visualize a file because it’s a
thing. That’s why VBA uses classes to describe the file system and uses objects
to work with individual file system elements, such as a drive. Although you
might read that objects are substitutes for procedures, the two kinds of pro-
gramming have definite places in your programmer’s toolbox. Make sure that
you work with both as needed.
183
Do'stlaringiz bilan baham: