10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

8.3.2 Initialization of Fields CLASSES<br />

202<br />

It is a compile-time error if the evaluation of a variable initializer for a static<br />

field of a named class (or of an interface) can complete abruptly with a checked<br />

exception (§11.2).<br />

It is compile-time error if an instance variable initializer of a named class can<br />

throw a checked exception unless that exception or one of its supertypes is explicitly<br />

declared in the throws clause of each constructor of its class and the class has<br />

at least one explicitly declared constructor. An instance variable initializer in an<br />

anonymous class (§15.9.5) can throw any exceptions.<br />

8.3.2.1 Initializers for Class Variables<br />

If a reference by simple name to any instance variable occurs in an initialization<br />

expression for a class variable, then a compile-time error occurs.<br />

If the keyword this (§15.8.3) or the keyword super (§15.11.2, §15.12)<br />

occurs in an initialization expression for a class variable, then a compile-time<br />

error occurs.<br />

One subtlety here is that, at run time, static variables that are final and that<br />

are initialized with compile-time constant values are initialized first. This also<br />

applies to such fields in interfaces (§9.3.1). <strong>The</strong>se variables are “constants” that<br />

will never be observed to have their default initial values (§4.12.5), even by devious<br />

programs. See §12.4.2 and §13.4.9 for more discussion.<br />

Use of class variables whose declarations appear textually after the use is<br />

sometimes restricted, even though these class variables are in scope. See §8.3.2.3<br />

for the precise rules governing forward reference to class variables.<br />

8.3.2.2 Initializers for Instance Variables<br />

Initialization expressions for instance variables may use the simple name of any<br />

static variable declared in or inherited by the class, even one whose declaration<br />

occurs textually later.<br />

Thus the example:<br />

class Test {<br />

float f = j;<br />

static int j = 1;<br />

}<br />

compiles without error; it initializes j to 1 when class Test is initialized, and initializes<br />

f to the current value of j every time an instance of class Test is created.<br />

Initialization expressions for instance variables are permitted to refer to the<br />

current object this (§15.8.3) and to use the keyword super (§15.11.2, §15.12).<br />

DRAFT

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!