Java Reference
In-Depth Information
￿ Suppose x is an identifier declared within a class and outside every
method's definition (block):
￿ If x is declared without the reserved word static (such as a named
constant or a method name), then it cannot be accessed within a
static method.
￿ If x is declared with the reserved word static (such as a named constant
or a method name), then it can be accessed within a method (block),
provided the method (block) does not have any other identifier named x .
Before considering an example that illustrates these scope rules, first note the scope of the
identifier declared in the for statement. Java allows the programmer to declare a variable in
the initialization statement of the for statement. For example, the following for statement:
for ( int count = 1; count < 10; count++)
System.out.println(count);
declares the variable count and initializes it to 1 . The scope of the variable count is only
limited to the body of the for loop.
Example 7-11 illustrates the scope rules.
7
EXAMPLE 7-11
public class ScopeRules
{
static final double rate = 10.50;
static int z;
static double t;
public static void main(String[] args)
{
int num;
double x, z;
char ch;
//...
}
public static void one( int x, char y)
{
//...
}
public static int w;
public static void two( int one, int z)
{
char ch;
int a;
Search WWH ::




Custom Search