CLASSES
Initialization of Fields
8.3.2
If the declarator is for a class variable (that is, a
static
 field), then the vari 
able initializer is evaluated and the assignment performed exactly once, when
the class is initialized ( 12.4).
If the declarator is for an instance variable (that is, a field that is not
static
),
then the variable initializer is evaluated and the assignment performed each
time an instance of the class is created ( 12.5).
The example:
class Point {
int x = 1, y = 5;
}
class Test {
public static void main(String[] args) {
Point p = new Point();
System.out.println(p.x + ", " + p.y);
}
}
produces the output:
1, 5
because the assignments to
x
 and
y
 occur whenever a new
Point
 is created.
Variable initializers are also used in local variable declaration statements
( 14.3), where the initializer is evaluated and the assignment performed each time
the local variable declaration statement is executed.
It is a compile time error if the evaluation of a variable initializer for a field of
a class (or interface) can complete abruptly with a checked exception ( 11.2).
8.3.2.1
Initializers for Class Variables
A compile time error occurs if an initialization expression for a class variable con 
tains a use by a simple name of that class variable or of another class variable
whose declaration occurs to its right (that is, textually later) in the same class.
Thus:
class Test {
static float f = j;
//
compile time error: forward reference
static int j = 1;
static int k = k+1;
//
compile time error: forward reference
}
causes two compile time errors, because
j
 is referred to in the initialization of
f
before
j
 is declared and because the initialization of
k
 refers to
k
 itself.
149






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Inexpensive Web Hosting  Jsp Web Hosting

Cheapest Web Hosting Jsp Hosting Cheap Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved