this
ReferenceEvery object can access a reference to itself with keyword this
(also called the this
reference). When a non-static
method (or property) is called for a particular object, the method’s body implicitly uses keyword this
to refer to the object’s instance variables and other non-static class members. As you’ll see in Fig. 10.4, you also can use keyword this
explicitly in a non-static
method’s body. Section 10.5 shows a more interesting use of keyword this
. Section 10.9 explains why keyword this
cannot be used in a static
method.
Figure 10.4 demonstrates implicit and explicit use of the this
reference to enable class ThisTest
’s Main
method to display the private
data of a SimpleTime
object. For the sake of brevity, we declare two classes in one file—class ThisTest
is declared in lines 5–12, and class SimpleTime
is declared in lines 15–42.
Class SimpleTime
declares three private
instance variables—hour
, minute
and second
(lines 17–19). The constructor (lines 24–29) receives three int
arguments to initialize a SimpleTime
object (without validation for simplicity). Here, we used parameter names that are identical to the class’s instance-variable names (lines 17–19). We did this intentionally to hide the corresponding instance variables so that we could illustrate explicit use of the this
reference. If a method contains a local variable with the same name as an instance variable, the local variable is said to shadow (or hide) the instance variable in the method’s body. However, you can use this
to access the hidden instance variable explicitly, as shown in lines 26–28 for SimpleTime
’s hidden instance variables.
Using properties throughout a class to access the class’s instance variables normally eliminates shadowing because property names use Pascal Case naming (capital first letter) and parameter names use Camel Case (lowercase first letter).
Method BuildString
(lines 32–34) returns a string
created by a statement that uses the this
reference explicitly and implicitly. Line 33 uses the this
reference explicitly to call method ToUniversalString
. Line 34 uses the this
reference implicitly to call the same method. Programmers typically do not use the this
reference explicitly to reference other methods in the current object. Also, line 41 in method ToUniversalString
explicitly uses the this
reference to access each instance variable. This is not necessary here, because the method does not have any local variables that hide the instance variables of the class.
Class ThisTest
(lines 5–12) demonstrates class SimpleTime
. Line 9 creates an instance of class SimpleTime
and invokes its constructor. Line 10 invokes the object’s BuildString
method, then displays the results.