How can a class have a member of its own type, isn’t this infinite recursion?

You’re only declaring the variable and not creating it. Try creating it at declaration or in the constructor and let me know what happens:

public class Abc {
   private Abc p = new Abc(); // have fun!

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

Incidentally, if you don’t create it in the class, but rather accept a reference to it in a getter method or a constructor parameter, your code will work just fine. This is how some linked lists work.

Leave a Comment