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:
- The return type of a constructor is void. Since it is a void method you can’t harness the complete power of recursion.
- A constructor can invoke itself (or any other constructor) using this(). But a “call to this must be first statement in constructor”
- We could use non local data between consecutive calls to still have some possible gain from recursive constructors.
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 anewexpression within a constructor:Here the
Nodeconstructor calls itself, but via a new expression. This is the crucial difference. Anewexpression 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.