Java Reference
In-Depth Information
What happens when two variables, say one instance variable and one local variable, are in scope in the same part
of a program? Let's consider the following code for the NameHidingTest2 class:
class NameHidingTest2 {
int n1 = 10; // An instance variable
/// m1 is a method
void m1() {
int n1 = 20; // A local variable
/* Both, instance variable n1 and local variable n1, are in scope here */
int n2 = n1; // What value is assigned to n2 - 10 or 20?
}
/* Only instance variable n1 is in scope here */
int n3 = n1; // n3 is assigned 10 from the instance variable n1
}
When the m1() method is executed in the above code, what value will be assigned to the variable n2 ? Note the
class declares an instance variable with the name n1 , and the method m1() also declares a local variable with the
name n1 . The scope of the instance variable n1 is the entire class body that includes the body of the m1() method. The
scope of the local variable n1 is the entire body of the m1() method. When the statement
int n2 = n1;
is executed inside the m1() method, two variables with the same name n1 are in scope: one has a value of 10 and one
has a value of 20 . Which n1 does the above statement refer to: n1 the instance variable, or n1 as the local variable?
When a local variable has the same name as the name of a class field, an instance/class variable, the local variable
name hides the name of the class field. This is known as name hiding. In the above case, the local variable name n1
hides the name of the instance variable n1 inside the m1() method. The above statement will refer to the local variable
n1 , not the instance variable n1 . Therefore, n2 will be assigned a value of 20 .
a local variable with the same name as a class field hides the name of the class field. In other words, when a
local variable as well as a class field with the same name are in the scope, the local variable takes precedence.
Tip
The following code for the class NameHidingTest3 clarifies the scenario when a local variable comes into scope:
public class NameHidingTest3 {
int n1 = 10; // An instance variable n1
public void m1() {
/* Only the instance variable n1 is in scope here */
int n2 = n1; // Assigns 10 to n2
 
 
Search WWH ::




Custom Search