Determining the Scope of Methods and Variables

Methods interact with variables and their associated data. But a method cannot interact with any variable. Certain methods and variables are designed to work together. A method designates the variables it wants to work with by exposing them with an EXPOSE instruction. The exposed methods are called object variables. Exposing variables confines them to an object; in object-oriented terms, they are encapsulated. This protects the object variables' data from being changed by "unauthorized" methods belonging to other objects.

Objects with a Class Scope

Encapsulation usually takes place at the class level. The class is designed as a template of methods and variables. The instances themselves retain only the values of their variables.

Within the hierarchy, the class structure ensures the integrity of a class's variables, controlling the methods allowed to operate on them. The class structure also provides for easy updating of the method code. If a method requires a change, you only have to change it once, at the class level. The change then is acquired by all the instances sharing the method.

Associated methods and variables have a certain scope, which is the class to which they belong:

Figure 6-3. Scope of the Number Class

Each class in a class hierarchy has a scope different from any other class. This is what allows a variable in a subclass to have the same name as a variable in a superclass, even though the methods that use the variables for completely unrelated purposes.

Objects with Their Own Unique Scope

The methods and variables used by instances in a class are usually found at the class level. But sometimes an instance differs in some respect from the others in its class. It might perform an additional action or require some unique handling. In this case one or more methods and related variables can be added directly to the instance. These additional methods and variables form a separate scope, independent of the class scopes found throughout the rest of the hierarchy.

Methods can be added directly to an instance's collection of object methods using SETMETHOD, a method of the Object class. All subclasses of the Object class inherit SETMETHOD. Alternately, the Class class provides an ENHANCED method that lets you create new instances of a class, whose object methods are the instance methods of its class, but enhanced with the additional collection methods.