Write a Program including This Keyword in Java
In earlier post of this keyword we have written a program which is related to this keyword. Since we didn’t use the this keyword, the default value (0,0) of data members are displayed. Now we will write the same program again but will include the this keyword this time. Check out the main difference and output too.
class th2
{
int a, b;
th2(int a, int b)
{
this.a=a;
this.b=b;
}
public void show()
{
System.out.println(a);
System.out.println(b);
}
public static void main(String[] args)
{
//new th2(20,30).show();
th2 t2=new th2(20,30);
t2.show();
}
}
The above program will display the output 20, 30. Check out the screen shot below
We have use this keyword in the constructor “th2″ because we want to refer to the parameter of the constructor not the data members. Due to the use of this keyword
this.a=a;
this.b=b;
The value passed to the parameter of the constructor is called rather than the data members value.
This program practically proved the statement 1 of the this keyword -
“this always refers to current object.”
Note: –
You can instantiate member referance in two ways
th2 t2 = new th2(20, 30);
t2.show();
or
new th2(20,30).show();
Share this Post[?]




