The constructor of wharves, bridges, piers, bulk-heads,
floats, stays against the sea . . .
Walt Whitman, Song of the Broad-Axe (1856)
A constructor is used in the creation of an object that is an instance of a class:
ConstructorDeclaration:
ConstructorModifiersoptConstructorDeclarator
ThrowsoptConstructorBody ConstructorDeclarator:
SimpleTypeName
(
FormalParameterListopt)
The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration; otherwise a compile-time error occurs. In all other respects, the constructor declaration looks just like a method declaration that has no result type.
class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } }
Constructors are invoked by class instance creation expressions (§15.8), by the newInstance
method of class Class
(§20.3), by the conversions and concatenations caused by the string concatenation operator + (§15.17.1), and by explicit constructor invocations from other constructors (§8.6.5). Constructors are never invoked by method invocation expressions (§15.11).
Access to constructors is governed by access modifiers (§6.6). This is useful, for example, in preventing instantiation by declaring an inaccessible constructor (§8.6.8).
Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.