Team LiB
Previous Section Next Section

Object Self-Referencing with "this"

In client code, such as the Main method of a program, we declare reference variables with which to store handles on objects:

Student s = new Student();  // s is a reference variable of type Student.

and can then conveniently access the objects that these reference variables refer to by manipulating the reference variables themselves:

s.Name = "Fred";

When we're executing the code that comprises the body of one of an object's own methods, we sometimes need the object to be able to refer to itself—i.e., to self-reference, as in this next bit of code:

public class Student
{
  Professor facultyAdvisor;
  // other details omitted
  public void SelectAdvisor(Professor p) {
    // We're down in the "bowels" of the SelectAdvisor() method,
    // executing this method for a particular Student object.

    // We save the handle on our new advisor as one of our fields ...
    facultyAdvisor = p;

    // ... and now we want to turn around and tell this Professor object to
    // add us as one of its (Student) advisees. The Professor class has a
    // method with signature:
    //
    //         public void AddAdvisee(Student s);
    //
    // so, all we need to do is call this method on our advisor object
    // and pass in a reference to ourselves; but who the heck are we?
    // That is, how do we refer to ourself?
    p.AddAdvisee(???);
  }
}

Within the body of a method, when we need a way to refer to the object whose method we're executing, we use the reserved word this to "self-reference." So, in our preceding example, the following line of code would do the trick:

p.AddAdvisee(this);

Specifically, it would pass a reference to this Student—the Student object whose method we're executing at this very moment—as an argument of the AddAdvisee method, to Professor p.

We mentioned back in Chapter 4 that we may invoke one method/feature of a class from within another method of the same class without using dot notation:

public class Student
{
  // details omitted

  public void MethodA() {
    // We can call MethodB from within MethodA without
    // using dot notation.
    MethodB();
    // other details omitted ...
  }
  public void MethodB() {
    // details omitted ...
  }
}

As it turns out, this is shorthand for the following equivalent dot notation:

public void MethodA() {
  // Calling MethodB from within MethodA.
  this.MethodB();
  // other details omitted ...
}

Since the this. prefix is implied, we needn't include it, but are free to do so if we wish.

We'll see yet another use for the this keyword, having to do with constructors, in a moment.


Team LiB
Previous Section Next Section