Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is variable shadowing used for in a Java class?

Tags:

java

shadowing

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);     } } 
like image 343
Jayson Avatar asked Jul 07 '09 12:07

Jayson


People also ask

What is variable shadowing in Java?

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).

What does shadowing a variable mean?

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.

What is variable hiding and shadowing?

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?

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.


1 Answers

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.

like image 111
Yishai Avatar answered Oct 14 '22 15:10

Yishai