8.6.5 Constructor Body

The first statement of a constructor body may be an explicit invocation of another constructor of the same class, written as this followed by a parenthesized argument list, or an explicit invocation of a constructor of the direct superclass, written as super followed by a parenthesized argument list.

ConstructorBody:
{ ExplicitConstructorInvocationopt BlockStatementsopt }
ExplicitConstructorInvocation:
this ( ArgumentListopt ) ;
super (
ArgumentListopt ) ;

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 is implicitly assumed by the compiler to begin 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, the body of a constructor is like the body of a method (§8.4.5). A return statement (§14.15) may be used in the body of a constructor if it does not include an expression.

In the example:


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;
}
}

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.

An explicit constructor invocation statement may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs. For example, if the first constructor of ColoredPoint in the example above were changed to:


	ColoredPoint(int x, int y) {
		this(x, y, color);
	}

then a compile-time error would occur, because an instance variable cannot be used within a superclass constructor invocation.

An invocation of the constructor of the direct superclass, whether it actually appears as an explicit constructor invocation statement or is provided automatically (§8.6.7), performs an additional implicit action after a normal return of control from the constructor: all instance variables that have initializers are initialized at that time, in the textual order in which they appear in the class declaration. An invocation of another constructor in the same class using the keyword this does not perform this additional implicit action.

§12.5 describes the creation and initialization of new class instances.