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.


The difference lies in compile-time vs run-time checks.

In the first case (compile time), you are declaring that you will have a reference to a value of type Abc in this instance. The compiler will be aware of this when it checks for proper semantics, and since it knows the type upon compile time, it sees no issue with this.

In the second case (run time), you will actually create a value for this reference to refer to. This is where you could potentially get yourself into trouble. For example, if you said the following:

public class Abc {
    private Abc p;

    public Abc() {
        p = new Abc();
    }
}

This could lead you into trouble for the exact reason you cited (recursion that contains no base case and will continually allocate memory until you've run the VM out of heap space).

However, you can still do something similar to this and avoid the infinite recursion. By avoiding creating the value during construction, you put it off until a method is called for. In fact, it's one of the common ways to implement the singleton pattern in Java. For example:

public class Abc {
    private Abc p;

    private Abc() {  // Private construction. Use singleton method
    }

    public static synchronized Abc getInstance() {
        if (p == null)
            p = new Abc();

        return p;
    }
}

This is perfectly valid because you only create one new instance of the value, and since run-time will have loaded the class already, it will know the type of the instance variable is valid.


When you want to model some real-world scenarios, you might have to use this notion. For example, think of a Tree's branch. A tree's branch might have n number of branches on it. Or from computer science background, think of a linked list's Node. A node will have reference to the node next to it. At the end, the next will contain a null to indicate end of the list.

So, this is only a reference, indicating that this type might refer to one of it's own. Nothing more.

Tags:

Java

Oop

Class