Description
Constructors are invoked by class instance creation expressions (i.e., by using
the new statement), by the newInstance method of class Class, by the
conversions and concatenations caused by the string concatenation operator +, and by
explicit constructor invocations from other constructors. Constructors are never
invoked by method invocation expressions.
Access to constructors is governed by the access modifiers public, protected, and private. This is useful, for example, in preventing instantiation by declaring an inaccessible constructor.
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.
If a constructor body does not begin with an explicit constructor invocation, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", that is, 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. A return statement may be used in the body of a constructor if it does not include an expression.
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided. The default constructor takes no parameters and simply invokes the superclass constructor with no arguments. If a default constructor is provided by the compiler but the superclass does not have a constructor that takes no arguments, a compilation error occurs.
Examples
In the following example, 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.
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; static final int 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; } }
class keyword
new keyword
private keyword
protected keyword
public keyword
return keyword
super keyword
this keyword
Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.