Nested Classes, Inner Class

Ins*_*ion 2 java constructor class call

I created an object d, right after the constructor, then another object, f, in the main method. I need to understand why is Output giving an exception (Exception in thread "main" java.lang.StackOverflowError). However, if I don't create the object d after the constructor, the program runs with success.

public class OuterTwo {
   public OuterTwo() {
       System.out.println("OUTER!");
   }

   OuterTwo d = new OuterTwo();

   public static void main(String[] args) {
       OuterTwo f = new OuterTwo();           
   }
}
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 5

Because your class is defined as having this field,

OuterTwo d = new OuterTwo();
Run Code Online (Sandbox Code Playgroud)

Which is equivalent to

OuterTwo d;
public OuterTwo() {
  d = new OuterTwo(); // <-- this is infinite recursion.
  System.out.println("OUTER!");
}
Run Code Online (Sandbox Code Playgroud)