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.
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
mainmethod, 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
mainmethod 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.