THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

A field cannot be both final and volatile.


When multiple modifiers are applied to the same field declaration, we recommend using the order listed
above.


2.2.1. Field Initialization


When a field is declared it can be initialized by assigning it a value of the corresponding type. In the Body
example, the nextID field is initialized to the value zero. The initialization expression, or more simply the
initializer, need not be a constant, however. It could be another field, a method invocation, or an expression
involving all of these. The only requirement is that the initializer be of the right type and, if it invokes a
method, no checked exceptions may be thrown because there is no surrounding code to catch the exception.
For example, the following are all valid initializers:


double zero = 0.0; // constant
double sum = 4.5 + 3.7; // constant expression
double zeroCopy = zero; // field
double rootTwo = Math.sqrt(2); // method invocation
double someVal = sum + 2*Math.sqrt(rootTwo); // mixed


Although initializers provide a great deal of flexibility in the way fields can be initialized, they are only
suitable for simple initialization schemes. For more complex schemes we need additional toolsas we shall
soon see.


If a field is not initialized a default initial value is assigned to it depending on its type:


Type Initial Value

boolean false

char '\u0000'

byte, short, int, long 0

float, double +0.0

object reference null

2.2.2. Static Fields


Sometimes you want only one instance of a field shared by all objects of a class. You create such fields by
declaring them static, so they are called static fields or class variables. When you declare a static field
in a class only one copy of the field exists, no matter how many instances of the class are created.


In our case, Body has one static field, nextID, which contains the next body identifier to use. The
nextID field is initialized to zero when the class is initialized after it is loaded (see "Loading Classes" on
page 435). You will see that each newly created Body object will be assigned the current value of nextID as
its identifier, and the value of nextID will be incremented. Hence, we only want one copy of the nextID
field, to be used when creating all Body instances.


Within its own class a static field can be referred to directly, but when accessed externally it must usually
be accessed using the class name. For example, we could print the value of nextID as follows:

Free download pdf