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.
In java you cannot create a method outside of a class. All methods must be encapsulated within a class. Therefore the main method as an entry point to the program must be within a class. When you run this program the main method will be run once and will execute the code inside it.
Yes, you can create object for the class which has main method.
It's OK for an object to have a pointer to another instance of the same class as a member, but it's not OK to create that instance in the constructor, or have it initialized in the body of the class, or you'lll recursively create objects until your stack overflows.
After it is created, you can add it back to the class with Employee. obj1 = obj1 . The reason for the extra step is that normally just can't create an instance of a class inside the class definition. Otherwise, you're calling a class that hasn't been defined yet.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With