Java Reference
In-Depth Information
The argument list determines which version of the constructor is in-
voked as part of the
new
expression.
If provided, an explicit constructor invocation must be the first state-
ment in the constructor. Any expressions that are used as arguments for
the explicit constructor invocation must not refer to any fields or meth-
ods of the current objectto all intents and purposes there is no current
object at this stage of construction.
For completeness, you could also provide a one-argument constructor
for constructing a
Body
object that doesn't orbit anything. This construct-
or would be used instead of invoking the two-argument
Body
constructor
with a second argument of
null
:
Body(String bodyName) {
this(bodyName, null);
}
and that is exactly what this constructor does, using another explicit
constructor invocation.
Some classes always require that the creator supply certain kinds of
data. For example, your application might require that all
Body
objects
have a name. To ensure that all statements creating
Body
objects supply
a name, you would define all
Body
constructors with a name parameter
and you wouldn't bother initializing the
name
field.
Here are some common reasons for providing specialized constructors:
•
Some classes have no reasonable initial state without paramet-
ers.
•
Providing an initial state is convenient and reasonable when
you're constructing some kinds of objects (the two-argument
constructor of
Body
is an example).