Exploring the “this” reference
When you call an instance method, the compiler secretly passes into the method a copy of the object reference that invoked the method. This reference is available to the instance method as the this
reference.
Class methods do not get a this
reference. This is why, if you are in a static
method (context) and you try to access an instance member directly (without an object reference), you will get a compiler error. In effect, every instance member requires an object reference when accessing it. This makes sense because instance members are instance-specific and therefore, you need an instance (reference) to say, “I want to access this particular instance/object as opposed to that particular one.”
Let’s refactor the code in Figure 8.3 so that the Person
class uses the this
reference explicitly. In addition, all references to the incorrectly working count
instance variable have been removed so that we can focus on...