Exercise – Shadowing
Write the code that demonstrates variable shadowing. We have not talked about it, so you will need to do some research.
Answer
Here is one possible solution:
public class ShadowingDemo { private String x = "x"; public void printX(){ System.out.println(x); String x = "y"; System.out.println(x); } }
If you run new ShadowingDemo().printX();
, it will print x
first, then y
because the local variable x
in the following line shadows the x
instance variable:
String x = "y";
Please note that shadowing can be a source of a defect or can be used for the benefit of the program. Without it, you would be not able to use a local variable identifier that is already used by an instance variable. And here is another example of a case where variable shadowing helps:
private String x = "x"; public void setX(String x) { this.x = x; }
The x
local variable (parameter) shadows the x
instance variable. It allows using the same identificator for a local variable name that has been...