this keyword in java

By
Advertisement
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. 

Situation-1:

     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.
import java.io.*;
class thisDemo{
int a,b;  
public void getData(int a, int b) 
{
a=a;
b=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(); 
obj.getData(2,3); 
obj.show(); 
}
}

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) 
{
this.a=a;
this.b=b;
}
     
When you call the above method using the object " obj" the above code is converted as

public void getData(int a, int b) 
{
obj.a=a;
obj.b=b;
}

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

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

import java.io.*;
class thisDemo2{
int x;
thisDemo2(){
 this(55);
 this.display();
}
thisDemo2(int x){
 this.x=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.

0 comments:

Post a Comment