Issue
public class TestClass(){
public static void main(String []args) {
TestClass t1 = new TestClass();
t1.anything();
}
}
Is it not strange to create a object in the definition of same class? Because then in response - this object creates a new object, then this new object creates another, and the infinite loop begins to never end until the memory is full.
Solution
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
}
}
Answered By - Rohit Jain
Answer Checked By - Timothy Miller (JavaFixing Admin)