0

Variable Hiding and Variable Shadowing in java

Are they same or there is any difference between them?

4th Jul 2017, 3:49 PM
Pintu
Pintu - avatar
2 odpowiedzi
+ 1
Yes, there is a difference. Variable hiding happens during inheritance and variable shadowing is within the same class. Variable hiding happens when the class that you extend from has a variable of the same name. class Parent { int children = 4; // code ......... } class Child extends Parent { int children = 1; // code .......... } The children variable of the Parent class is hidden by the children variable of the Child class. This is similar to overriding a method of the Parent class. You can still access the children variable of the Parent class from the Child class by using the super keyword. super.children; Variable shadowing happens within the same class. class My class { int count = 0; void myMethod() { int count = 4; } } When count is referred to within the myMethod it will see the count variable that is declared in that method. You can still access the count variable of the class by using the this keyword. this.count;
4th Jul 2017, 5:45 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
thank you ChaoticDawg. Now i think, i ll never forget this concept.
4th Jul 2017, 7:27 PM
Pintu
Pintu - avatar