Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

class

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.

like image 731
Ravi Kumar Mistry Avatar asked Oct 24 '12 07:10

Ravi Kumar Mistry


People also ask

Can I create an object of a class inside that class?

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.

Can we create object of class in a method?

Yes, you can create object for the class which has main method.

Can you create an instance of a class within the same class?

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.

Can we create object of a class inside the same class python?

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.


1 Answers

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      } } 
like image 179
Rohit Jain Avatar answered Sep 18 '22 17:09

Rohit Jain