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?
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:
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.