Video lecture
Watch on YouTube(opens in a new tab)Sub topic 9
Scope and Shadowing
What scope means
A variable’s scope is the part of a program where you can refer to it by name. Scope matters because it controls where a name is available. It also lets you use a name for a short task without keeping it around everywhere.
A block is a group of Java statements inside matching braces, { and }. A local variable is a variable declared inside a method or block. Its scope usually runs from its declaration to the end of the block that contains it.
A method is a named set of instructions. A variable declared inside a method cannot be used in a different method just because both methods are in the same class.
For example, if you declare int total = 5; inside an if block, you can use total later in that block. You cannot use it after the block’s closing brace.
Fields, parameters, and local variables
A class is a blueprint for creating objects. An object is a value created from a class. A field is a variable declared in a class, outside its methods. An instance field belongs to an object.
A parameter is a variable that receives a value when a method is called. A parameter is available throughout that method’s body.
A field and a parameter can have the same name. When they do, the parameter shadows the field inside the method. Shadowing means that a nearer declaration hides another declaration with the same name.
The field still exists. In an instance method, use this.fieldName to reach the field. The word this refers to the current object: the object whose method is running.
Worked example
Save this program as Room.java. Compile it with javac Room.java, then run it with java Room.
public class Room {
int temperature = 20;
void show(int temperature) {
System.out.println("Parameter: " + temperature);
System.out.println("Field: " + this.temperature);
if (temperature > 25) {
int difference = temperature - this.temperature;
System.out.println("Difference: " + difference);
}
for (int step = 1; step <= 2; step++) {
System.out.println("Step: " + step);
}
System.out.println("Parameter again: " + temperature);
}
public static void main(String[] args) {
Room room = new Room();
room.show(28);
}
}The program prints these lines, in order:
Parameter: 28Field: 20Difference: 8Step: 1Step: 2Parameter again: 28
In main, new Room() creates an object. The call room.show(28) passes 28 to the show method. Inside show, the parameter named temperature receives that value.
The object also has a field named temperature, with the value 20. Inside show, the parameter shadows the field:
temperaturemeans the parameter.this.temperaturemeans the field of the currentRoomobject.
The two variables are separate. If you assign 30 to temperature inside show, you change the parameter, not the field. To change the field, you could write this.temperature = 30;.
The diagram shows where the declarations belong. The parameter is available in both inner blocks. The field is also available there as this.temperature.
Scope inside blocks
The if statement in the example checks whether the parameter is greater than 25. Its block declares difference.
You can use difference after its declaration and before the closing brace of that block. You cannot print difference after the if block ends. If you try, Java reports an error because the name is not in scope there.
An inner block can use a variable from an enclosing block. In the example, the if block can read the temperature parameter. But the enclosing method body cannot use the inner block’s difference after that block ends.
A name is not available before its declaration. For example, moving the print statement for difference above the line that declares it would cause an error.
Loop variables
A loop repeats a set of instructions. In the example, the for loop declares step in its first part. The scope of step includes the loop’s condition, its update, and its body.
After the loop ends, step is out of scope. A statement after the loop cannot print that variable.
If a value must be used after a block or loop, declare it in an enclosing block instead. Choose that wider scope only when it is needed. A smaller scope makes it easier to see where a variable can be used or changed.
When names can be reused
Java allows the parameter temperature to have the same name as the field. But it does not allow every kind of name reuse.
You cannot declare a local variable with the same name as another local variable or parameter that is still in scope in an enclosing block. For example, adding int temperature = 30; inside the if block of show would cause an error: the parameter temperature is already in scope there.
Once a local variable’s scope has ended, its name can be reused. For example, two separate, non-overlapping blocks in the same method may each declare a local variable named message. Each message is available only in its own block.
A field can also be shadowed by a local variable. As with a parameter, use this.fieldName to refer to the field from an instance method when a local variable shadows it.
Common mistakes
Using a name outside its scope
A variable declared inside an if block or loop is not automatically available after it. Check which braces contain the declaration. If the closing brace has passed, the variable may be out of scope.
Using a variable before its declaration
A local variable must be declared before you use it. Being in the same block is not enough.
A variable also needs a value before you read it. This is a separate issue from scope: a name can be in scope even when Java does not yet allow you to read its value.
Changing the wrong variable
If a parameter or local variable shadows a field, an assignment to the plain name changes the nearer variable. Use this.fieldName when you mean the current object’s field.
You cannot use this inside main as written above. The word static means that main belongs to the class rather than to a particular object. There is no current object for this to refer to there. The program instead creates a Room object and calls show on it.
Choosing the same name without a reason
Shadowing is useful when a parameter naturally has the same name as a field. But too many repeated names can make code hard to read. Use clear names and keep scopes small.
Practice
Exercise
In the Room program, what do temperature and this.temperature mean inside show when room.show(28) is called?
Show answer
temperature is the parameter with value 28. this.temperature is the current Room object's field with value 20.
Exercise
Can show print difference immediately after the if block? Why?
Show answer
No. difference is declared inside the if block, so it is out of scope after that block ends.
Exercise
Could you add int temperature = 30; inside the if block in show?
Show answer
No. The temperature parameter is still in scope, so Java does not allow that overlapping local declaration.