Bhushan
Bhushan

Reputation: 6181

Use of invoking constructor within same constructor

public class MyClass {
    public static void main(String args[]) {
        new MyClass();
    }
    public MyClass() {
        new MyClass();
    }
}

In above code, a constructor is invoked within the same constructor.

The Output of above code is famous java.lang.StackOverflowError, because a constructor is invoked until the error occurs.

My question is what are the real scenarios in which invoking a constructor within the same constructor is useful?

Upvotes: 1

Views: 48

Answers (2)

Stephen C
Stephen C

Reputation: 718758

I am sure one could invent a scenario, but making constructors recursive is not generally a useful thing to do. Generally speaking, when a constructor calls new on the same class, it is a mistake.


Here is a contrived example in which we use recursion to construct a list of N copies of the same value.

   public class MyList {
       private int value;
       private MyList next;

       public MyList(int value, int length) {
           this.value = value;
           if (length > 1) {
              next = new MyList(value, length - 1);
           }
       }
   }

(And, yes, there are flaws in this approach ...)

Upvotes: 3

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

It might be useful in situations where recursive loop is broken at some point - for example with if statement:

class LinkedList {

    Object value;
    LinkedList next;

    public LinkedList(final Iterator<?> iterator) {
        this.value = iterator.next();
        if (iterator.hasNext()) {
            this.next = new LinkedList(iterator);
        }
    }
}

This will call constructor recursively as long as there are elements available in iterator.

Upvotes: 3

Related Questions