I'm reading my Deitel, Java How to Program book and came across the term shadowing. If shadowing is allowed, what situation or what purpose is there for it in a Java class?
Example:
public class Foo { int x = 5; public void useField() { System.out.println(this.x); } public void useLocal() { int x = 10; System.out.println(x); } }
If the instance variable and local variable have same name whenever you print (access) it in the method. The value of the local variable will be printed (shadowing the instance variable).
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking.
Variable Hiding happens when a variable declared in the child class has the same name as the variable declared in the parent class. In contrast, variable shadowing happens when a variable in the inner scope has the same name as the variable in the outer scope.
What does it mean for a local variable to shadow a field? A method may have a local variable with the same name as an instance field. This is called shadowing. The local variable will hide the value of the instance field. Shadowing is discouraged and local variable names should not be the same as instance field names.
The basic purpose of shadowing is to decouple the local code from the surrounding class. If it wasn't available, then consider the following case.
A Class Foo in an API is released. In your code you subclass it, and in your subclass use a variable called bar. Then Foo releases an update and adds a protected variable called Bar to its class.
Now your class won't run because of a conflict you could not anticipate.
However, don't do this on purpose. Only let this happen when you really don't care about what is happening outside the scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With