Thursday 19 March 2015

The this Keyword in Java

         this keyword in java is a reference variable which refers to the current object which invoked it. 

Syntax:
this.variable_name=variable_name;

    In this article you can see the usage of this keyword to refer current class instance variable. Lets discuss with an example. The below example is to calculate the Area of triangle. 



Output:






In the example
1) b,h are the variable of the class TriangleArea.
2)g,k are the formal parameters of the method SetValue.
3)Once you call the method SetValue with Object and actual parameters the values of g,k will be assigned to b.h respectively.
4) If both the class variable name and formal parameter name in the method are same then what will happen. See the below example . (The formal parameter name g,h is replaced with the name b,h )



Output:

 



Why So?
Here the formal parameter value is not assigned to the class variable b,h. It has been assigned to itself . Because the scope of the class variable has been replaced by the formal parameter. (Will discuss more about ‘scope’ later)

How to overcome this?
See the below example . The class variable is used with the keyword ‘this’.



Output:

 



Here this.b and this.h refers the current class instance variable instead the formal parameter.

Other usage of this keyword
this() keyword can be used to invoke current class constructor .
this keyword can be used to invoke current class method.
this keyword can be used to pass as argument in the constructor call.
this keyword can be used to return the current class instance.
this keyword can be used to pass an argument in the method call .

We will discuss each of the usage in detail later.



No comments: