- this holds the reference of current object. Observe below
example:
class demo
{
int x=10;
void show(int x,demo d1)
{
System.out.println(this.x);
System.out.println(d1.x);
System.out.println(x);
}
public static void
main(String…s)
main(String…s)
{
demo d1=new
demo();
demo();
d1.show(20,d1);
}
}
Output:
10
10
20
- In Java by default this is passed to all non static methods.
- this cannot be used into static methods.
- this is the reference variable or local variable, it goes to
stack. - When local and global variables are same then this situation
is known as data shadowing. In such situation this keyword is used to
distinguish between local and global variable.
Consider below example:
class demo
{
int x=10;
void show()
{
int x=20;
System.out.println(this.x); //golabal variable
System.out.println(x); //local variable, priority goes to local variable
}
public static void
main(String…s)
main(String…s)
{
demo d=new
demo();
demo();
d.show();
}
}
Output
10
20
Watch below video tutorial to understand this keyword easily