Categories
Java

Usage of ‘this’ keyword in java

It always holds the reference of the current object.It can be used in the following situations

1.this can be used to refer current class instance variable.

2.this can be used to invoke current class method (implicitly).

3.this() can be used to invoke current class constructor.

4.this can be passed as an argument in the method call.

5.this can be passed as an argument in the constructor call.

6.this can be used to return the current class instance from the method.

when the names of the formal arguments and names of the properties of current object are same,to refer the properties of the current object ‘this’ operator is used.
The following java program explains the above mentioned point.

class Exam
{
int a,b;
void set(int a,int b)
{
this.a=a;
this.b=b;
}
void show()
{
System.out.println(a+"\t"+b);
}
}
class ExamMain
{
public static void main(String arg[])throws Exception
{
Exam e=new Exam();
e.set(10,20);
e.show();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *