Java Reference
In-Depth Information
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 initial-
ized 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 depend-
ing on its type:
Type
Initial Value
boolean
false
char
'\u0000'
 
Search WWH ::




Custom Search