9.8. Using the Me Reference to Access the Current ObjectEvery object of a class shares the class's method declarations. We have seen that an object's methods can manipulate the object's data. But how do methods know which object's instance variables to manipulate? Every object has access to itself through a reference called Me (a Visual Basic keyword). On every method call, the compiler passes an object's Me reference as an implicit argument to each of the object's non-Shared methods. The Me reference can then be used to access a particular object's members implicitly or explicitly. (Section 9.10 introduces Shared class members and explains why the Me reference is not implicitly passed to Shared methods.) Class Time (Fig. 9.8) defines Private instance variables hour, minute and second (lines 46). The constructor (lines 914) receives three Integer arguments to initialize a Time object. For this example, we use parameter names (lines 910) that are identical to the class's instance variable names (lines 46). When a method has a parameter or local variable with the same name as one of the class's instance variables, the instance variable is shadowed (hidden) in the method's scope. However, the method can use the Me reference to refer explicitly to shadowed instance variables. Lines 1113 of Fig. 9.8 demonstrate this feature. Method BuildString (lines 1720) returns a String created by a statement that uses the Me reference first explicitly then implicitly. Line 18 uses the Me reference explicitly to call method ToUniversalString, whereas line 19 calls the same method using the Me reference implicitly. Note that both lines generate identical outputs. Figure 9.8. Class using the Me reference.
Error-Prevention Tip 9.2
Error-Prevention Tip 9.3
Module MeTest (Fig. 9.9) demonstrates the Me reference. Line 5 instantiates a Time object. Line 6 invokes method BuildString, then displays the results to the user. Figure 9.9. Me reference demonstration.
|