Use One : The first use of this is it refer to the class variable when the parameter variable or method variable hides the class variable.
class This1
{
int a;
This1(int a)
{
this.a = a;
}
public static void main(String args[])
{
This1 m = new This1(10);
System.out.println(m.a);
}
}
OUTPUT : 10
class This2
{
int x=10;
void met()
{
int x = 40;
System.out.println(x);
System.out.println(this.x);
}
public static void main(String args[])
{
This2 m = new This2();
m.met();
System.out.println(m.x);
}
}
OUTPUT : 40
10
10
Use Two: The second use of this is to call another constructor of the same class from within a constructor by passing appropriate arguments.
Web Site Form Database
Name : Name Salary
Salary : Yes Yes
OK No (Unknown) Yes
Yes No (0)
No (Unknown) No (0)
class This3
{
String name;
int sal;
This3(String s, int i)
{
name=s;
sal=i;
System.out.println("Name : "+name);
System.out.println("Salary : " + sal);
}
This3(String s)
{
this(s,0);
}
This3(int i)
{
this("Unknown",i);
}
This3()
{
this(0);
}
public static void main(String args[])
{
This3 w = new This3("Maya", 1000);
This3 x = new This3("Sangeeta");
This3 y = new This3(5000);
This3 z = new This3();
}
}
OUTPUT :
Name : Maya
Salary : 1000
Name : Sangeeta
Salary : 0
Name : Unknown
Salary : 5000
Name : Unknown
Salary : 0