The this Reference

 

Introduction.  In this webpage we will present some background on what is called the this reference or keyword.   We have  been making use of it for some time when adding actionListener to JButtons.  There are also plenty of other uses!

Within the body of a method you may want to refer to the current object, that is the object the current method was invoked on.  That is,

currentObject.currentMethod( )

This can happen when trying to make use of this particular object's instance variables.  Or it might happen in order to pass the object to another method.

In order to do this you may use the this keyword or reference.  The this reference can be used to access both instance variables and methods of the object.  For example,

  • currentHour = this.hour;
  • currentHour = this.getHour( )

Due to the nature of the this reference it should only be used with instances of an object within methods that are instance method definitions.  Class methods, that is methods declared using the static keyword cannot make use of the this reference.