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

前端 未结 6 1711
野的像风
野的像风 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:34

    public class TestClass{
      public static void main(String []args) {
        TestClass t1 = new TestClass();
        t1.anything();
      }
    }
    

    This is a perfectly valid code. When the main method is called, no prior instance of the TestClass exists (it needs not, because the main method is static).

    public class Test2{
      public Test2 clone(){
        return new Test2();
      }
    }
    

    This is perfectly valid as well. When you create a new instance of Test2, it contains the clone method, but the method is not automatically executed. Only when the clone method is called, one more instance of Test2 is created.

    public class MyLinkedList{
      MyLinkedList next;
      MyLinkedList(int elems){
        if(elems>0){
          next = new MyLinkedList(elems-1);
        }else{
          next = null;
        }
      }
    }
    

    is perfectly valid as well, even if the constructor creates a new instance using the same constructor, because the creation is guarded by a conditional, so creating an instance sometimes triggers a new creation.

    public class Fail{
      public Fail(){
        new Fail();
      }
    }
    

    Is the only problematic example here. The compiler doesn't complain. It can be translated into byte code and it can be executed. At the runtime, however, you cause a stack overflow:

    • a new Fail is allocated
    • its no-arg constructor is called
    • the constructor tries to create a new Fail
    • a new Fail is allocated
    • its no-arg constructor is called
    • ...

    The compiler allows this, because, in general, the compiler cannot prevent all infinite recursion. The compiler allows anything that can be translated into bytecode.

    The compiler, however, may issue a warning if it detects a method or a method chain calls itself unconditionally.

提交回复
热议问题