THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

3.2.1. Constructor Order Dependencies


When an object is created, memory is allocated for all its fields, including those inherited from superclasses,
and those fields are set to default initial values for their respective types (zero for all numeric types, false
for boolean, '\u0000' for char, and null for object references). After this, construction has three
phases:



  1. Invoke a superclass's constructor.

  2. Initialize the fields using their initializers and any initialization blocks.

  3. Execute the body of the constructor.


First the implicit or explicit superclass constructor invocation is executed. If an explicit this constructor
invocation is used then the chain of such invocations is followed until an implicit or explicit superclass
constructor invocation is found. That superclass constructor is then invoked. The superclass constructor is
executed in the same three phases; this process is applied recursively, terminating when the constructor for
Object is reached because there is no superclass constructor at that point. Any expressions evaluated as part
of an explicit constructor invocation are not permitted to refer to any of the members of the current object.


In the second stage all the field initializers and initialization blocks are executed in the order in which they are
declared. At this stage references to other members of the current object are permitted, provided they have
already been declared.


Finally, the actual statements of the constructor body are executed. If that constructor was invoked explicitly,
then upon completion, control returns to the constructor that invoked it, and executes the rest of its body. This
process repeats until the body of the constructor used in the new construct has been executed.


If an exception is thrown during the construction process, the new expression terminates by throwing that
exceptionno reference to the new object is returned. Because an explicit constructor invocation must be the
first statement in a constructor body, it is impossible to catch an exception thrown by another constructor. (If
you were allowed to catch such exceptions it would be possible to construct objects with invalid initial states.)


Here is an example you can trace to illustrate the different stages of construction:


class X {
protected int xMask = 0x00ff;
protected int fullMask;


public X() {
fullMask = xMask;
}


public int mask(int orig) {
return (orig & fullMask);
}
}


class Y extends X {
protected int yMask = 0xff00;


public Y() {


fullMask |= yMask;
}
}

Free download pdf