Using this

Purpose:

To refer to the current instance

Mechanics:

this.<method name>(); // Call a method on this instance
this.<instance variable>; // Refer to this instance's state
this // A reference to this instance

Example:

this.myMethod();

Usage:

  • <method name> is any method that can be called on the current instance. The current instance is the instance that a method was called on. If a method name appears in a method with no instance, it is assumed that the method has an implicit this -- and the current instance should send the method to itself.
  • If the name of a parameter of the method is the same identifier as an instance variable of the class which contains the method, then Java will assume that a reference to that identifier is a reference to the parameter, not the instance variable. A statement can refer to the instance variable by referring to this.<instance variable>.
  • The first line of a constructor is often a call to super(<parameter list>). If constructors have been overloaded for a class, the first line of any of those constructors could instead be a call to this (<paramter list>), invoking another constructor with a different paramter list.

Restrictions:

A static method cannot refer to this since static methods exist on a class, not an instance, level.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu