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.