The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).
ConstructorBody:
{ [ExplicitConstructorInvocation] [BlockStatements] }
It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
Except for the possibility of explicit constructor invocations, and the prohibition on explicitly returning a value (§14.17), the body of a constructor is like the body of a method (§8.4.7).
A return statement (§14.17) may be used in the body of a constructor if it does not include an expression.
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. Explicit Constructor Invocations
ExplicitConstructorInvocation:
[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}
Explicit constructor invocation statements 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.
- Unqualified superclass constructor invocations begin with the keyword
An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.
This prohibition on using the current instance explains why an explicit constructor invocation statement is deemed to occur in a static context (§8.1.3).
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 statement 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.
If a superclass constructor invocation statement 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
pbe 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 ofpis not O or a subclass of O, or if the type ofpis not accessible (§6.6).
The exception types that an explicit constructor invocation statement can throw are specified in §11.2.2.
Evaluation of an alternate constructor invocation statement proceeds by first evaluating the arguments to the constructor, left-to-right, as in an ordinary method invocation; and then invoking the constructor.
Evaluation of a superclass constructor invocation statement proceeds as follows:
-
Let
ibe the instance being created. The immediately enclosing instance ofiwith respect to S (if any) must be determined:-
If S is not an inner class, or if the declaration of S occurs in a static context, then no immediately enclosing instance of
iwith respect to S exists. -
If the superclass constructor invocation is unqualified, then S is necessarily a local class or an inner member class.
If S is a local class, then let O be the immediately enclosing type declaration of S.
If S is an inner member class, then let O be the innermost enclosing class of C of which S is a member.
Let n be an integer (n ≥ 1) such that O is the n'th lexically enclosing type declaration of C.
The immediately enclosing instance of
iwith respect to S is the n'th lexically enclosing instance ofthis.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,thisitself) is never used as the immediately enclosing instance of i with respect to S. -
If the superclass constructor invocation is qualified, then the Primary expression or the ExpressionName immediately preceding "
.super",p, is evaluated.If
pevaluates tonull, aNullPointerExceptionis raised, and the superclass constructor invocation completes abruptly.Otherwise, the result of this evaluation is the immediately enclosing instance of
iwith respect to S.
-
-
After determining the immediately enclosing instance of
iwith respect to S (if any), evaluation of the superclass constructor invocation statement proceeds by evaluating the arguments to the constructor, left-to-right, as in an ordinary method invocation; and then invoking the constructor. -
Finally, if the superclass constructor invocation statement 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
Itextually precedes another instance initializer or instance variable initializerJ, thenIis executed beforeJ.Execution of instance variable initializers and instance initializers is performed regardless of whether the superclass constructor invocation actually appears as an explicit constructor invocation statement or is provided implicitly. (An alternate constructor invocation does not perform this additional implicit execution.)
Example 8.8.7.1-1. Restrictions on Explicit Constructor Invocation Statements
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 explicit constructor invocation statement.
Example 8.8.7.1-2. Qualified Superclass Constructor Invocation
In the code below, ChildOfInner has no lexically enclosing type declaration, so an instance of ChildOfInner has no enclosing instance. However, the superclass of ChildOfInner (Inner) has a lexically enclosing type 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 statement 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 statement. The rules for an explicit constructor invocation statement do not prohibit using formal parameters of the constructor that contains the statement.
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.