"THIS" Keyword in Java
'THIS' keyword is a reference variable in Java that refers to current object.
The various usages of 'THIS' keyword in Java are as follows: -
1.It can be used to return the current class instance.
2.It can be passed as an argument in the method call.
3.It can be passed as argument in the constructor call.
4. can be used to refer instance variable of current class.
5.can be used to invoke or initiate current class constructor.
Example: -
class Account
{
int a;
int b;
public void setData(int a ,int b)
{
a = a;
b = b;
}
public void showData()
{
System.out.println("Value of A ="+a); System.out.println("Value of B ="+b);
}
public static void main(String args[])
{
Account obj = new Account(); obj.setData(2,3);
obj.showData();
}
}
Value of a & b is shown as zero? To correct the error append line # 6 & 7 with "this" keyword.
this.a=a;
this.b=b;
This time around, values of a & b are set to 2 & 3 respectively.
Summary: -
1.Keyword 'THIS' in Java is a reference variable that refers to the current object.
2.It can be used to refer current class instance variable.
3.It can be used to invoke or initiate current class constructor.
4.It can be passed as an argument in the method call.
5.It can be passed as argument in the constructor call.
6.It can be used to return the current class instance.
7."this" is a reference to the current object, whose method is being called upon.
8.You can use "this" keyword to avoid naming conflicts in the method/constructor of your instance/object.
No comments :
Post a Comment