In Java, constructors cannot be recursive. Compile time error: "recursive constructor invocation". Let's assume that we did not have this restriction.
Things to keep in mind:
Would there be any benefit from allowing recursive constructors?
Constructors (when they are calling each other) are like methods that return void
. Consequently the only way they can produce results is by side-effects. This is then limited to mutating the object they are constructing or by mutating the values passed in as parameters. The latter is a pretty nasty idea in a constructor; a constructor usually takes information from its parameters without mutating them.
So mutating the object being constructed is the only option in order to have any way to track the progress of the recursion, in order for it to terminate eventually. And it's very hard to see how that would be easier to write, clearer to read, etc. than a simple loop inside an ordinary constructor.
Calling another constructor (with this
) from within a constructor is of course totally different from using a new
expression within a constructor:
class Node
{
Node _left, _right;
public Node(Node left, Node right)
{
_left = left != null ? new Node(left._left, left._right) : null;
_right = right != null ? new Node(right._left, right._right) : null;
}
}
Here the Node
constructor calls itself, but via a new expression. This is the crucial difference. A new
expression produces a value, so this is purely "functional", non-mutating stuff, and provides a convenient way to make a deep copy of the tree of nodes.