Java Interview Question

Use this intermediate question and answer to prepare for your next Java interview.

Can you create an object of a class within the same class? Can this lead to an error?

Yes, you can instantiate a class within itself. Example:

Class A {
  A a = new A(); // Valid instantiation
  A b;
  public A() {
    b = new A(); // Error line

The line commented as Error line is an example of self-object instantiation leading to an error. In this case, the JVM will allocate stack space on each constructor call, and the stack will soon run out of space leading to a StackOverflowError, a common recursion problem.

Looking for developers?