Java Reference
In-Depth Information
This is a useful technique when a number of constructors share a significant
amount of initialization code, as it avoids repetition of that code. In more complex
cases, where the constructors do a lot more initialization, this can be a very useful
technique.
There is an important restriction on using
this()
: it can appear only as the first
statement in a constructor—but the call may be followed by any additional initiali‐
zation a particular constructor needs to perform. The reason for this restriction
involves the automatic invocation of superclass constructors, which we'll explore
later in this chapter.
Field Defaults and Initializers
The fields of a class do not necessarily require initialization. If their initial values are
not specified, the fields are automatically initialized to the default value
false
,
\u0000
,
0
,
0.0
, or
null
, depending on their type (see
Table 2-1
for more details).
These default values are specified by the Java language specification and apply to
both instance fields and class fields.
If the default field value is not appropriate for your field, you can instead explicitly
provide a different initial value. For example:
public
static
final
double
PI
=
3.14159
;
public
double
r
=
1.0
;
Field declarations are not part of any method. Instead, the Java
compiler generates initialization code for the field automati‐
cally and puts it into all the constructors for the class. The ini‐
tialization code is inserted into a constructor in the order in
which it appears in the source code, which means that a field
initializer can use the initial values of any fields declared
before it.
Consider the following code excerpt, which shows a constructor and two instance
fields of a hypothetical class:
public
class
SampleClass
{
public
int
len
=
10
;
public
int
[]
table
=
new
int
[
len
];
public
SampleClass
()
{
for
(
int
i
=
0
;
i
<
len
;
i
++)
table
[
i
]
=
i
;
}
// The rest of the class is omitted...
}
In this case, the code generated by
javac
for the constructor is actually equivalent to
the following: