this keyword in java

The java this keyword is act as default reference to your class. This keyword refers to the object of the class where it is used. In other words, this refers to the object of  the present class. Generally when we create a class, all the class members are referenced by this keyword. So, this is class a default reference to your class. 

Where the keyword this is useful ?

                There are some situations where this can be used explicitly by the programmer 
  • When the local variables and reference variables have the same name then the program give wrong results. To solve this we use this keyword
  • When constructor overloading is done, to call the same class constructors we use this keyword. 


     When the local variables and refrence variables have the same name the expected results are not seen in the output. For example, consider the following program, where a, b are instance variables as well as reference variables.
class thisDemo{
int a,b;  
public void getData(int a, int b) 
public void show(){
System.out.println(" A value is =" +a);
System.out.println(" B value is =" +b);
public static void main(String args[]){
thisDemo obj= new thisDemo(); 

I am creating an object called " obj" , then I have passed values to the getData() method and finally I displayed a, b values using show() method. Then what are expected values of a , b ? is the program display 2,3 ? let us see the out put....!!

So, from the above scree short what are the results of a, b values program results are 0,0. Why this is happening is when both instance variables and reference variables are same, the JVM is unable to assign or refer the variables inside the method call.So, There are two solutions to solve this problem,

1. Use different names for instance variables and reference variables.
2. Use this reference in front of reference variable like

public void getData(int a, int b) 
When you call the above method using the object " obj" the above code is converted as

public void getData(int a, int b) 

That is the keyword " this" is replaced by object of that class.

                     When constructor overloading is done, one can call the other overloaded methods of the same class using "this" keyword as

class thisDemo2{
int x;
thisDemo2(int x){
void display(){
 System.out.println(" x value is ="+x);
public static void main( String args[]){
 thisDemo2 d2=new thisDemo2();

The above program will results the following output

X value is = 55.


Post a Comment