this Keyword
Example: To learn the use "this" keyword
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();
}
}
Example of this keyword in Java for Variable Hiding
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();
}
}
Example of this with Constructor
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();
}
}
Example of this keyword as Method parameter
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();
}
}
this Keyword with Method
class JBT {
public static void main(String[] args) {
JBT obj = new JBT();
obj.methodTwo();
}
void methodOne(){
System.out.println("Inside Method ONE");
}
void methodTwo(){
System.out.println("Inside Method TWO");
this.methodOne();// same as calling methodOne()
}
}
Keyword 'THIS' in Java is a reference variable that refers to the current object.
It can be used to refer current class instance variable
It can be used to invoke or initiate current class constructor
It can be passed as an argument in the method call
It can be passed as argument in the constructor call
It can be used to return the current class instance
"this" is a reference to the current object, whose method is being called upon.
You can use "this" keyword to avoid naming conflicts in the method/constructor of your instance/object.