Shadowing occurs when you define a method with input parameters that have names identical to a static variables or instance variables.
Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents.
If you analyze the next sequence
class Auto {
int maxSpeed;
float weight;
//constructor with parameters
public Auto(int maxSpeed, float Weight) {
//shadowing
//Assignment to itself warning
maxSpeed = maxSpeed;
weight = Weight;
}
public void setMaxSpeed(int maxSpeed) {
//shadowing
//Assignment to itself warning
maxSpeed = maxSpeed;
}
public int getMaxSpeed() {
return this.maxSpeed;
}
}
public class Main {
public static void main(String[] args) {
Auto a = new Auto(180, 2000);
System.out.println(a.getMaxSpeed());
a.setMaxSpeed(200);
System.out.println(a.getMaxSpeed());
}
}
then you will see that the Auto() method (constructor) and the setMaxSpeed() have an input parameter, maxSpeed with a name equal with the instance variable.
Running the example, you get as output
0
0
because the input parameter is shadowing the instance variable inside the 2 methods. Based on the code logic we want to initialize the instance variable with the argument value, but when the methods are compiled, the left maxSpeed variable is seen as the local variable and not as the instance variable. The compiler even warns you for a possible error with the Assignment to itself warning message.
In this case, it is important to use this reference in order to indicate which variable is the instance variable. So the correct for of the example is:
class Auto {
int maxSpeed;
float weight;
//constructor with parameters
public Auto(int maxSpeed, float Weight) {
//using this to show the instance variable
this.maxSpeed = maxSpeed;
weight = Weight;
}
public void setMaxSpeed(int maxSpeed) {
//using this to show the instance variable
this.maxSpeed = maxSpeed;
}
public int getMaxSpeed() {
return this.maxSpeed;
}
}
For static variables, you can’t use this reference to avoid shadowing because static variables are class variables and not instance variables. In this case, you use the class name, like this:
class Auto {
static int category;
int maxSpeed;
float weight;
public static void setCategory(int category)
{
//using class name to show the instance variable
Auto.category = category;
}
}
Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents.