The
keyword this is a non-static final
referenced variable used to store current object reference to separate
non-static variable of different objects in non-static context. In compilation
phase compiler places this keyword
in all non-static members call if they are called directly by their name.
1. If there is ambiguity between the
instance variable and parameter, this keyword resolves the problem of
ambiguity.
Example –
public class
Test2 {
int x;
int y;
public
Test2(int x,int y)
{
this.x=x; //this.x refers to instance variable and x refers
to parameter
this.y=y;
}
public void
show()
{
System.out.println("The value of a and y is : "+x+" and
"+y);
}
public static void
main(String[] args) {
Test2 t = new
Test2(10, 20);
t.show();
}
}
Output –
The value of a and y is : 10
and 20
2. To invoke current class
constructor
Example –
public class
Test2 {
int x;
int y;
public
Test2()
{
System.out.println("default constructor is invoked");
}
public
Test2(int x,int y)
{
this();
this.x=x; //this.x refers to instance variable and x refers
to parameter
this.y=y;
}
public void
show()
{
System.out.println("The value of a and y is : "+x+" and
"+y);
}
public static void
main(String[] args) {
Test2 t = new
Test2(10, 20);
t.show();
Test2 t1 = new
Test2(50,20);
t1.show();
}
}
Output –
default constructor is invoked
The value of a and y is : 10 and 20
default constructor is invoked
The value of a and y is : 50
and 20
Note – Call to this() must be
the first statement in constructor.
3. The this keyword can be used to
invoke current class method (implicitly)
Example –
public class
Test2 {
public void
m1()
{
System.out.println("HEllo java");
}
public void
m2()
{
this.m1();
}
public void
m3()
{
m2(); //
compiler converts it to this.m2()
}
public static void
main(String[] args) {
Test2 t = new
Test2();
t.m3();
}
}
Output –
HEllo java
No comments:
Post a Comment