Search code examples
javalate-binding

How does JAVA allow class instantiation within the class?


Am new to JAVA. Am wondering over the following construct:

class MyClass {
    private MyClass myClass;
//whatever
}

How is it that this does not cause infinite recursion? Is it only due to late-binding?


Solution

  • Depends on what exactly is the question. There are two reasons: one static (why it compiles) and one dynamic (why it runs):

    • Firstly, in Java you never need to know the size of objects in advance, because all objects are allocated on heap and you cannot have one object within another (you can only store references to things, not the things themselves).

    • Secondly, the field in your code is created with a null reference. To create a new instance in Java you always need new

    So, your example compiles and works. If you changed the line to:

    private MyClass myClass = new MyClass();
    

    you would get a stack overflow when trying to initialize MyClass.