Tuesday, 3 July 2012

this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the thiskeyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use 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 w, double h, double d) { 
this.width = w; 
this.height = h; 
this.depth = d; 
}
The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking 
object.

No comments:

Post a Comment