jason jason - 5 months ago 27
Java Question

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

Say I define a class that has as a member a variable of the same type as itself.

public class abc {
private abc p;
}


This actually works, much to my surprise.

Why I think it shouldn't: creating an instance of
abc
, it contains a variable of type
abc
, which contains a variable of type
abc
, which contains a variable of type
abc
, which .....

Obviously I'm wrong, could someone enlighten me as to how?

Answer

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.