Thursday, 13 October 2011

this keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object.

The this Keyword refers to the object that is currently  executing .this is always reference to the object on which the method was invoked. this keyword can be  used inside any method to refer to the current object.

For Ex,
  class Data
  {
            int no;
            String name;
            Data(int n,String nm)
            {
                      this.no=n;
                      this.name=nm;
            }
}

Here the instance variable of class data can be referred with the this keyword which belongs to the invoking object.

Hiding instance variable 

when a local variable has the same name as an instance variable the local variable hides the instance variable.this  can be used to resolve any name space collision that might occur between instance variables and local variables.

Ex,
class Data
  {
            int no;
            String name;
            Data(int no,String name)
            {
                      this.no=no;
                      this.name=name;
            }
}

          Here, the parameters of constructor have the same name as the class instance variable so it hide the original member variable. This is used to refer the class variable.

Posted by:Ruchita Pandya

2 comments: