THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The initializers for name and orbits set them to reasonable values. Therefore, when the constructor returns
from the following invocations, all data fields in the new Body object have been set to some reasonable initial
state. You can then set state in the object to the values you want:


Body sun = new Body(); // idNum is 0
sun.name = "Sol";


Body earth = new Body(); // idNum is 1
earth.name = "Earth";
earth.orbits = sun;


The Body constructor is invoked when new creates the object but after name and orbits have been set to
their default initial values.


The case shown herein which you know the name of the body and what it orbits when you create itis likely to
be fairly common. You can provide another constructor that takes both the name and the orbited body as
arguments:


Body(String bodyName, Body orbitsAround) {
this();
name = bodyName;
orbits = orbitsAround;
}


As shown here, one constructor can invoke another constructor from the same class by using the this()
invocation as its first executable statement. This is called an explicit constructor invocation. If the constructor
you want to invoke has arguments, they can be passed to the constructor invocationthe type and number of
arguments used determines which constructor gets invoked. Here we use it to invoke the constructor that has
no arguments in order to set up the idNum. This means that we don't have to duplicate the idNum
initialization code. Now the allocation code is much simpler:


Body sun = new Body("Sol", null);
Body earth = new Body("Earth", sun);


The argument list determines which version of the constructor is invoked as part of the new expression.


If provided, an explicit constructor invocation must be the first statement in the constructor. Any expressions
that are used as arguments for the explicit constructor invocation must not refer to any fields or methods 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 constructor 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.

Free download pdf