Java Reference
In-Depth Information
variables and parameters. Example 4-4 illustrates the different kinds of fields and
variables that may be accessible to a local class:
Example 4-4. Fields and variables available to a local class
class A { protected char a = 'a' ; }
class B { protected char b = 'b' ; }
public class C extends A {
private char c = 'c' ; // Private fields visible to local class
public static char d = 'd' ;
public void createLocalObject ( final char e )
final char f = 'f' ;
int i = 0 ; // i not final; not usable by local class
class Local extends B
char g = 'g' ;
public void printVars ()
// All of these fields and variables are accessible to this class
System . out . println ( g ); // (this.g) g is a field of this class
System . out . println ( f ); // f is a final local variable
System . out . println ( e ); // e is a final local parameter
System . out . println ( d ); // (C.this.d) d field of containing class
System . out . println ( c ); // (C.this.c) c field of containing class
System . out . println ( b ); // b is inherited by this class
System . out . println ( a ); // a is inherited by the containing class
Local l = new Local (); // Create an instance of the local class
l . printVars (); // and call its printVars() method.
Lexical Scoping and Local Variables
A local variable is defined within a block of code that defines its scope , and outside
of that scope, a local variable cannot be accessed and ceases to exist. Any code
within the curly braces that define the boundaries of a block can use local variables
defined in that block.
This type of scoping, which is known as lexical scoping , just defines a section of
source code within which a variable can be used. It is common for programmers to
think of such a scope as temporal instead—that is, to think of a local variable as
existing from the time the JVM begins executing the block until the time control
exits the block. This is usually a reasonable way to think about local variables and
their scope.
Search WWH ::

Custom Search