Java Reference
In-Depth Information
return values;
}
}
9.13 The Scope of Variables
The scope of instance and static variables is the entire class, regardless of where the
variables are declared.
Key
Point
Section 6.9 discussed local variables and their scope rules. Local variables are declared and
used inside a method locally. This section discusses the scope rules of all the variables in the
context of a class.
Instance and static variables in a class are referred to as the class's variables or data fields .
A variable defined inside a method is referred to as a local variable . The scope of a class's
variables is the entire class, regardless of where the variables are declared. A class's variables
and methods can appear in any order in the class, as shown in Figure 9.20a. The exception is
when a data field is initialized based on a reference to another data field. In such cases, the
other data field must be declared first, as shown in Figure 9.20b. For consistency, this topic
declares data fields at the beginning of the class.
class's variables
public class Circle {
public double findArea() {
return radius * radius * Math.PI;
public class F {
private int i ;
private int j = i + 1 ;
}
}
private double radius = 1 ;
}
(a) The variable radius and method findArea() can
be declared in any order.
(b) i has to be declared before j because j 's initial
value is dependent on i .
F IGURE 9.20
Members of a class can be declared in any order, with one exception.
You can declare a class's variable only once, but you can declare the same variable name
in a method many times in different nonnesting blocks.
If a local variable has the same name as a class's variable, the local variable takes precedence
and the class's variable with the same name is hidden . For example, in the following program,
x is defined both as an instance variable and as a local variable in the method.
public class F {
private int x = 0 ; // Instance variable
private int y = 0 ;
hidden variables
public F() {
}
public void p() {
int x = 1 ; // Local variable
System.out.println( "x = " + x);
System.out.println( "y = " + y);
}
}
What is the output for f.p() , where f is an instance of F ? The output for f.p() is 1 for x
and 0 for y . Here is why:
x is declared as a data field with the initial value of 0 in the class, but it is also
declared in the method p() with an initial value of 1 . The latter x is referenced in the
System.out.println statement.
y is declared outside the method p() , but y is accessible inside the method.
 
 
 
Search WWH ::




Custom Search