this Keyword

This keyword is used to refer current object. Whenever a method is called on a object, internally a reference variable is passed into that method which is used to access calling object's attributes. That reference variable is "this".

It can be better understand with help of following example.


Example


	  //file: stat.java 
// www.jgyan.com
class stat
{
int a;
stat(int a)
{
a=a; // compiler use argument of constructor to refer a. This statement won't assign value of argument to class data member
}
void show()
{
System.out.println("data member:"+a);
}
}
class tw
{
public static void main(String arg[])
{
stat s=new stat(20);
s.show();
}
}
/*Output:
data member:0
*/

In above example we have created a object by passing a argument. This argument value should have been assigned to data member a of object s. But value of a is 0. Reason for this behaviour is that in constructor of class stat, when statement "a = a" encountered java search whether a is argument or data member. Java find argument 'a' and then it assign value of argument 'a' to itself. Data member of class is initialised to default value.


To differentiate between instance variable 'a' and argument 'a', "this" keyword can be used.

Example :


		  // file : stat.java
// www.jgyan.com
class stat
{
int a;
stat(int a)
{
this.a=a; // compiler use argument of constructor to refer a. This statement won't assign value of argument to class data member
}
void show()
{
System.out.println("data member:"+a);
}
}
class tw
{
public static void main(String arg[])
{
stat s=new stat(20);
s.show();
}
}
/*Output:
data member:20
*/


Explicit Constructor invocation

this can be used to call another constructor inside a class. Code given below using this to call another constructor. In default constructor "this(0,0,false)" making a call to another constructor with three parameter. This feature is also known as explicit constructor invocation.


	  //file: stat.java
// www.jgyan.com
class stat
{
int a,b;
boolean flag;
stat()
{
this(0,0,false);
}
stat(int a)
{
this(a,0,false);
}
stat(int a,int b,boolean flag)
{
this.a=a;
this.b=b;
this.flag=flag;
}
void show()
{
System.out.println("a:"+a);
System.out.println("b:"+b);
System.out.println("flag:"+flag);
}
}
class tw
{
public static void main(String arg[])
{
stat s=new stat(20);
s.show();
}
}
/*Output:
a:20
b:0
flag:false
*/