Forum : THIS KEYWORD
Brief description  about Online courses   join in Online courses
View neeraj  khatri 's Profile

THIS KEYWORD

hello sir,
please tell me detail view of THIS KEYWORD and explain logical.
Asked by neeraj khatri | Aug 2, 2010 |  Reply now
Replies (2)
View neeraj khatri 's Profile
Thank u sir.
Aug 6, 2010
View arun kumar das 's Profile
Hi Neeraj,

Assume that you have several books with you and you would like to specifically point at a book you are holding in your hand. In this case you would shout out saying "I am talking about THIS book in my hand." Here you are pointing out a particular book out of a set of books using the word THIS.

In a similar way if we have to use a particular variable or a method or a constructor we will tell the compiler which one to use with the help of THIS keyword.

Let's take an example:
________________________________
private string this_example;
void method_name(string this_example)
{
this.javaFAQ = javaFAQ;
}
}
____________________________________
In the above example there are 2 variables with the same name:
1. string this_example which is outside the method is called INSTANCE variable.
2. string this_example which is the parameter name is called LOCAL variable.

By default, priority of local variable is higher than the instance variable. By using THIS keyword we are telling the compiler that we are referring to instance variable and not local variable. In our example within the method we are referring instance variable, if we had not used the keyword THIS then by default it would have referred to local variable.

I a similar way, THIS keyword is also used to refer constructors, pass parameters and so on.

Hope this helped you in understanding THIS keyword.

Cheers,
Java Teacher

Aug 4, 2010