'this' keyword in java
‘This’ keyword is used to initialize the global/instance variable. This helps to resolve the compiler’s confusion with the parameter when the global and local variable has the same name.
package test;
public class TestThisKeyword {
int a ;
int b ;
public void test1(int a, int b) {
a = a;
b = b;
}
public void test2() {
System.out.println("Print the value of a : "+a);
System.out.println("Print the value of b : "+b);
}
public static void main(String[] args) {
PracticeAll obj = new PracticeAll();
obj.test1(1,2);
obj.test2();
}
}
Output:
Print the value of a : 0
Print the value of b : 0
Explanation: The compiler gets confused with the variable a in test1(), compiler does not know left side variable is instant variable or local variable. So it can not assign the given value to the variable.
//-----------------------------------------------------------------------------------
This confusion arises because of the same name of the instance and local variable.
In below example the confusion is resolved by giving different names.
public class TestThisKeyword {
int a ;
int b ;
public void test1(int x, int y) {
a = x;
b = y;
}
public void test2() {
System.out.println("Print the value of a : "+a);
System.out.println("Print the value of b : "+b);
}
public static void main(String[] args) {
PracticeAll obj = new PracticeAll();
obj.test1(1,2);
obj.test2();
}
}
Output:
Print the value of a : 1
Print the value of b : 2
Use of THIS keyword:
When the local and instance variable have same name then we can overcome the problem by using THIS keyword as below. After using the keyword, the compiler knows the left hand side is the instance variable and the right hand side is the local variable.
public class TestThisKeyword {
int a ;
int b ;
public void test1(int a, int b) {
this.a = a; //this is like obj.a = a;
this.b = b; //this is like obj.b = b;
}
public void test2() {
System.out.println("Print the value of a : "+a);
System.out.println("Print the value of b : "+b);
}
public static void main(String[] args) {
PracticeAll obj = new PracticeAll();
obj.test1(1,2);
obj.test2();
}
}
Output:
Print the value of a : 1
Print the value of b : 2
No comments:
Post a Comment