Monday, 30 January 2012

this keyword in Java

•It is common for a class to contain instance variables and methods.
•It is also common for methods to have parameters.
•So, what happens when the names of instance variables and the parameters are same?
•In the above case the parameters “hide” the instance variables. This is an ambiguous situation.

•For example let’s have a look at the following piece of code…


class Box
{
   int length, width, height;
   void setDim(int length, int width, int height)
  {
    length = length;
    width = width;
    height = height;
  }
}



•In the example we just saw, the names of instance variables and names of parameters are same.
•How to solve this issue? There are two ways to solve this.
1) To change the names of parameters.
2) Using “this” keyword.
•The “this” keyword always refers to the current object.
•“this” can be used to resolve the naming conflicts between instance variables and parameters.
•So, by using the “this” keyword, our program can be return as follows…


class Box
{
    int length, width, height;
    void setDim(int length, int width, int height)
    {
      this.length = length;
      this.width = width;
      this.height = height;
    }
}

No comments:

Post a Comment