next up previous
Next: Use of this Up: Unit 03 Previous: Definition of methods

The implicit formal parameter this

All the instance (i.e., non-static) methods have an implicit formal parameter denoted by this. Such a parameter denotes the invocation object. In other words, when the method is called, this is bound to the (reference to) the invocation object, which thus acts as an actual parameter.

The parameter this is used to access the instance variables and the methods of the invocation object. Note that, in general, we can omit this, as we have done till now. Indeed, Java inserts it automatically whenever we use an instance variable or an instance method of the class.

Example: The definition of the class Person given below has exactly the same meaning as the class Person that we have already seen.

public class Person {
  //instance variables (data fields)
  private String name;
  private String residence;

  //methods (operation fields)
  public String getName() {
    return this.name;
  }
  public String getResidence() {
    return this.residence;
  }
  public void setResidence(String newResidence) {
    this.residence = newResidence;
  }
}

Note: We cannot assign a value to the formal parameter this. Note that, if we could, it would mean that we would actually change the invocation object of the method.


next up previous
Next: Use of this Up: Unit 03 Previous: Definition of methods