this Keyword
- this is a pointer that points to the current object
- this keyword is used when a method need to refer to the object that invoked it.
- this can be used inside any method to refer to the current object
- Consider the following Example:
//redundant use of this
Box(double w, double h, double d)
{
this.width=w;
this.height=h;
this.depth=d;
}
Instance Variable Hiding
- It is illegal in java to declare two local variables with the same name inside the same or enclosing scopes.
- We have local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables.
- However, when a local variable has the same name as an instance variable, the local variable hides the instance variable.
- This is why width, height and depth were not used as the names of the parameters to the Box() constructor inside the box class.
- If they had been, then width would have referred to the formal parameter, hiding the instance variable width. While it is easier to use different names.
- this can be used to resolve any name space collisions that might occur between instance variables and local variables because it refers to the current object
- For example, here is another version of Box(), which uses width, height, and depth for parameter names and then uses this to access the instance variables by the same name.
// use of this to resolve naming collisions.
Box(double width, double height, double depth)
{
this.width=width;
this.height=height;
this.depth=depth;
}