Java this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword.

The this keyword can be used inside any method to refer to the current object i.e., this always a reference to the object on which the method was invoked. You can use the this anywhere a reference to an object of the current class type is permitted.

To better understand what this refers to, consider the following version of Box() :

/* a redundant use of this */
Box(double wid, double hei, double dep)
{
   this.width = wid;
   this.height = hei;
   this.depth = dep;
}

This version of Box() operates exactly like the earlier version. The use of this is redundant, but perfectly correct. Inside the Box(), this will always refer to the invoking object. While it is redundant in this case, this is useful in other contexts.

Java Online Test


« Previous Tutorial Next Tutorial »