Local Variable Hides Instance Variable
In java when the local variable has
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Test { int a=10, b=10;// instance variable a,b public static void main(String agrs[]) { Test t = new Test(); t.display(); } public void display() { int a = 5;//local variable same name as instance variable System.out.println("Value of local variable a=" + a); System.out.println("Value of instance variable a=" + a + " b=" + b); } } |
Result
1 2 3 | Value of local variable a=5 Value of instance variable a=5 b=10 |
In above program we have two instance variable with value a=10 and b=10. in method display there is a local variable a with value 5.
Inside method display() local variable a hides the instance variable a and it prints local variable’s value that is 5.
To resolve this problem we use this keyword
this keyword
“this” keyword can be used inside any method to refer to
In Java, we can’t declare two local variables with the same name
When the local variable has Java same name as an instance variable, the local variable hides the instance variable. “this” keyword solve the
above problem can solve as given here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Test { int a=10, b=10;// instance variable a,b public static void main(String agrs[]) { Test t = new Test(); t.display(); } public void display() { int a = 5;//local variable same name as instance variable System.out.println("Value of local variable a=" + a); System.out.println("Value of instance variable a=" + this.a + " b=" + b); } } |
Result
1 2 3 | Value of local variable a=5 Value of instance variable a=10 b=10 |
Les see another example where we pass parameter to constructor and assign that value to instance variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class ThisKeyword { int a, b; // instance variable a,b ThisKeyword() { // default constructor “ThisKeyword” System.out.println("Inside default constructor"); } ThisKeyword(int a, int b) { // parameterized constructor “thisDemo” with local variable a,b System.out.println("parameterized constructor"); this.a = a; // “a” refers local variable and “this.a” refers instance variable this.b = b; // “b” refers local variable and “this.b” refers instance variable } void area() { System.out.println("value of a =" + a + " and b=" + b); } } public class ThisKeywordTest { public static void main(String arg[]) { ThisKeyword obj1 = new ThisKeyword(10, 10); ThisKeyword obj2 = new ThisKeyword(5, 5); obj1.area(); obj2.area(); } } |
Result
1 2 3 4 | parameterized constructor parameterized constructor value of a =10 and b=10 value of a =5 and b=5 |