When is it OK to create object of a class inside a method of that class?

Is it not strange to create an object in the definition of the same class than in response the object create a new object then this new object create another and the infinite loop begins

No, the main method only runs once when you run your program. It will not be executed again. So, the object will be created only once.

Think of your main method to be outside your class. Which creates an instance of your class, and uses the instance created. So, when you create an instance from main method, the constructor is invoked to initialize the state of your instance, and then when the constructor returns, the next statement of your main method is executed.

Actually, you can consider main method not to be a part of the state of the instance of your class.

However, had you created the instance of your class inside your constructor (say 0-arg), and the reference as instance reference variable, then that will turn into an infinite recursion.

public class A {
    private A obj;
    public A() {
        obj = new A();  // This will become recursive creation of object.
                        // Thus resulting in StackOverflow 
    }
}

You would only have an infinite loop (stack overflow error) if you tried to do the below:

public class TestClass {
    public TestClass() {
        TestClass t = new TestClass();
    }
}

And elsewhere, you try to create an object of the class TestClass.

Tags:

Java

Class