JVM Knowledge

A constructor body is a block of code that is executed as part of the process of creating a new instance of a class (§12.5). A constructor body may contain an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).

ConstructorBody:
  { [BlockStatements] ConstructorInvocation [BlockStatements] }
  { [BlockStatements] }

If a constructor body contains an explicit constructor invocation, the BlockStatements preceding the constructor invocation are called the prologue of the constructor body. The prologue of a constructor body may be empty. The BlockStatements in a constructor with no explicit constructor invocation and the BlockStatements following a constructor invocation in a constructor body are called the epilogue. The epilogue of a constructor body may also be empty.

A construct (statement, local variable declaration statement, local class declaration, local interface declaration, or expression) occurs in the early construction context of a class C if it is contained in either the prologue of a constructor body of C, or it is nested in the constructor invocation (§8.8.7.1) of a constructor body of C.

If a constructor body does not contain an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body (i) has an empty prologue, (ii) implicitly begins with a superclass constructor invocation "super();", an implicit invocation of the constructor of the direct superclass that takes no arguments, and (iii) the statements, if any, given in the constructor body are taken to form the epilogue of the constructor body.

Except for the possibility of explicit or implicit constructor invocations, and the prohibition on return statements (§14.17), the body of a constructor is like the body of a method (§8.4.7).

Note that a constructor body contains at most one constructor invocation. The grammar makes it impossible, for example, to place constructor invocations in different branches of an if statement.

Example 8.8.7-1. Constructor Bodies

class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
}
class ColoredPoint extends Point {
    static final int WHITE = 0, BLACK = 1;
    int color;
    ColoredPoint(int x, int y) {
        this(x, y, WHITE);
    }
    ColoredPoint(int x, int y, int color) {
        super(x, y);
        this.color = color;
    }
}

Here, the first constructor of ColoredPoint invokes the second, providing an additional argument; the second constructor of ColoredPoint invokes the constructor of its superclass Point, passing along the coordinates.

8.8.7.1. Constructor Invocations

ConstructorInvocation:
  [TypeArguments] this ( [ArgumentList] ) ;
  [TypeArguments] super ( [ArgumentList] ) ;
  ExpressionName . [TypeArguments] super ( [ArgumentList] ) ;
  Primary . [TypeArguments] super ( [ArgumentList] ) ;

The following productions from §4.5.1 and §15.12 are shown here for convenience:

TypeArguments:
  < TypeArgumentList >

ArgumentList:
  Expression {, Expression}

Constructor invocations are divided into two kinds:

  • Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.

  • Superclass constructor invocations begin with either the keyword super (possibly prefaced with explicit type arguments) or a Primary expression or an ExpressionName. They are used to invoke a constructor of the direct superclass. They are further divided:

    • Unqualified superclass constructor invocations begin with the keyword super (possibly prefaced with explicit type arguments).
    • Qualified superclass constructor invocations begin with a Primary expression or an ExpressionName. They allow a subclass constructor to explicitly specify the newly created object's immediately enclosing instance with respect to the direct superclass (§8.1.3). This may be necessary when the superclass is an inner class.

It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more alternate constructor invocations.

A constructor invocation introduces an early construction context (§8.8.7), which limits the use of constructs that refer to the current object. Notably, references to the current object using this and super are restricted in an early construction context (§15.8.3, §15.11.2), as are references to instance variables (§6.5.6.1) and instance methods (§6.5.7.1).

If TypeArguments is present to the left of this or super, then it is a compile-time error if any of the type arguments are wildcards (§4.5.1).

Let C be the class being instantiated, and let S be the direct superclass of C.

If a superclass constructor invocation is unqualified, then:

  • If S is an inner member class, but S is not a member of a class enclosing C, then a compile-time error occurs.

    Otherwise, let O be the innermost enclosing class of C of which S is a member. C must be an inner class of O (§8.1.3), or a compile-time error occurs. If the superclass constructor invocation occurs in an early construction context of the class O, then a compile-time error occurs.

  • If S is an inner local class, and S does not occur in a static context, let O be the immediately enclosing class or interface declaration of S. C must be an inner class of O, or a compile-time error occurs.

  • If S is an inner local class whose declaration occurs in a static context, then let N be the nearest static method declaration, static field declaration, or static initializer that encloses the declaration of S. If N is not the nearest static method declaration, static field declaration, or static initializer that encloses the superclass constructor invocation, then a compile-time error occurs.

If a superclass constructor invocation is qualified, then:

  • If S is not an inner class, or if the declaration of S occurs in a static context, then a compile-time error occurs.
  • Otherwise, let p be the Primary expression or the ExpressionName immediately preceding ".super", and let O be the immediately enclosing class of S. It is a compile-time error if the type of p is not O or a subclass of O, or if the type of p is not accessible (§6.6).

The exception types that an explicit constructor invocation can throw are specified in §11.2.2.

Evaluation of an alternate constructor invocation proceeds by first evaluating the arguments to the constructor, left-to-right, as in an ordinary method invocation; and then invoking the constructor.

Let i be the instance being created by a superclass constructor invocation. The immediately enclosing instance of i with respect to S (if any) is determined as follows:

  • If S is not an inner class, or if the declaration of S occurs in a static context, then no immediately enclosing instance of i with respect to S exists.

  • Otherwise, if the superclass constructor invocation is unqualified, then S is necessarily an inner local class or an inner member class.

    If S is an inner local class, let O be the immediately enclosing class or interface declaration of S.

    If S is an inner member class, let O be the innermost enclosing class of C of which S is a member. If the superclass constructor invocation occurs in the early construction context of the class O, then a compile-time error occurs.

    Let n be an integer (n ≥ 1) such that O is the n'th lexically enclosing class or interface declaration of C.

    The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of this.

    While it may be the case that S is a member of C due to inheritance, the zeroth lexically enclosing instance of this (that is, this itself) is never used as the immediately enclosing instance of i with respect to S.

  • Otherwise, if the superclass constructor invocation is qualified, then the immediately enclosing instance of i with respect to S is the object that is the value of the Primary expression or the ExpressionName.

If the superclass constructor invocation has an immediately enclosing instance then this instance is taken to be the first actual argument to the constructor invocation, and the subsequent actual arguments to the constructor invocation are taken to be the arguments in the argument list of superclass constructor invocation, if any, in the order that they appear. Otherwise the actual arguments to the constructor invocation are taken to be the arguments in the superclass constructor invocation, if any, in the order that they appear.

Evaluation of a superclass constructor invocation then proceeds as follows:

  1. First, if the superclass constructor invocation is qualified, the Primary expression or the ExpressionName is evaluated. If it evaluates to null, a NullPointerException is raised and the superclass constructor invocation completes abruptly. If this evaluation completes abruptly, then the superclass constructor invocation completes abruptly for the same reason.

  2. The actual arguments to the constructor invocation are evaluated, left-to-right, as in an ordinary method invocation; then the constructor is invoked.

    Recall that the first actual argument to the constructor invocation may be an enclosing instance.

  3. Finally, if the superclass constructor invocation completes normally, then all instance variable initializers of C and all instance initializers of C are executed. If an instance initializer or instance variable initializer I textually precedes another instance initializer or instance variable initializer J, then I is executed before J.

    Execution of instance variable initializers and instance initializers is performed regardless of whether the superclass constructor invocation actually appears as an explicit constructor invocation or is provided implicitly. (An alternate constructor invocation does not perform this additional implicit execution.)

Example 8.8.7.1-1. Restrictions on Constructor Invocations

If the first constructor of ColoredPoint in the example from §8.8.7 were changed as follows:

class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
}
class ColoredPoint extends Point {
    static final int WHITE = 0, BLACK = 1;
    int color;
    ColoredPoint(int x, int y) {
        this(x, y, color);  // Changed to color from WHITE
    }
    ColoredPoint(int x, int y, int color) {
        super(x, y);
        this.color = color;
    }
}

then a compile-time error would occur, because the instance variable color cannot be used by a constructor invocation.

Example 8.8.7.1-2. Qualified Superclass Constructor Invocation

In the code below, ChildOfInner has no lexically enclosing class or interface declaration, so an instance of ChildOfInner has no enclosing instance. However, the superclass of ChildOfInner (Inner) has a lexically enclosing class declaration (Outer), and an instance of Inner must have an enclosing instance of Outer. The enclosing instance of Outer is set when an instance of Inner is created. Therefore, when we create an instance of ChildOfInner, which is implicitly an instance of Inner, we must provide the enclosing instance of Outer via a qualified superclass invocation in ChildOfInner's constructor. The instance of Outer is called the immediately enclosing instance of ChildOfInner with respect to Inner.

class Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner() { (new Outer()).super(); }
}

Perhaps surprisingly, the same instance of Outer may serve as the immediately enclosing instance of ChildOfInner with respect to Inner for multiple instances of ChildOfInner. These instances of ChildOfInner are implicitly linked to the same instance of Outer. The program below achieves this by passing an instance of Outer to the constructor of ChildOfInner, which uses the instance in a qualified superclass constructor invocation. The rules for a constructor invocation do not prohibit using formal parameters of the constructor that contains the invocation.

class Outer {
    int secret = 5;
    class Inner {
        int  getSecret()      { return secret; }
        void setSecret(int s) { secret = s; }
    }
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner(Outer x) { x.super(); }
}

public class Test {
    public static void main(String[] args) {
        Outer x = new Outer();
        ChildOfInner a = new ChildOfInner(x);
        ChildOfInner b = new ChildOfInner(x);
        System.out.println(b.getSecret());
        a.setSecret(6);
        System.out.println(b.getSecret());
    }
}

This program produces the output:

5
6

The effect is that manipulation of instance variables in the common instance of Outer is visible through references to different instances of ChildOfInner, even though such references are not aliases in the conventional sense.