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

前端 未结 6 1717
野的像风
野的像风 2021-02-01 05:15
public class TestClass(){
    public static void main(String []args) {
        TestClass t1 = new TestClass();
        t1.anything();
    }
}

Is it not

6条回答
  •  星月不相逢
    2021-02-01 05:49

    When a program starts it executes the main method. 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. In your case it creates an object of the enclosing class TestClass. This does not have to happen. It can create objects outside of this class as well. You will only get an infinite loop as explained in the @adarshr's answer.

提交回复
热议问题