What is the shadow variable used in a Java class?

I am reading a Deitel book, Java, How to Program, and came across the term “shading”. If shading is allowed, what is the situation or what is the purpose for it in the 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); } } 
+22
java shadowing
Jul 07 '09 at 12:43
source share
5 answers

The main purpose of shading is to separate the local code from the surrounding class. If it is not available, consider the following case.

Foo class released in API. In your code, you subclass it, and in your subclass use the bar variable. Foo then releases the update and adds the protected variable Bar to its class.

Now your class will not be launched due to a conflict that you could not expect.

However, do not do this on purpose. Just let it happen when you really don't care about what happens outside the scope.

+36
Jul 07 '09 at 12:56
source share

This can be useful for setters, where you do not want to create a separate variable name only for a method parameter, for example:

 public void setX(int x) { this.x = x; } 

In addition, I would avoid them.

+13
Jul 07 '09 at 12:45
source share

One of the main goals is to confuse people. This is bad practice and should be avoided.

+9
Jul 07 '09 at 12:44
source share

Tendering is not really just a java term. In any case, when a variable declared in a region has the same name as in a wider space, this variable is obscured.

Some common uses for shadow copy are when you have inner and outer classes and you want to keep the variable with the same name.

If you can avoid this, you should, as this can cause confusion.

+5
Jul 07 '09 at 12:47
source share

Two common uses are constructors and set methods:

 public Foo(int x) { this.x = x; } public void setX(int x) { this.x = x; } 

Very often useful if you want to copy a variable at one time, but the variable can change in the method call.

 private void fire() { Listener[] listeners = this.listeners; int num = listeners.length; for (int ct=0; ct<num; ++ct) { listeners[ct].stateChanged(); } } 

(Of course, the far-fetched example made it unnecessary with the posh for loop.)

+2
Jul 07 '09 at 13:02
source share



All Articles