为什么当我尝试在它自己的 class 中创建对象时显示 stackoverflowerror?

Why is it showing stackoverflowerror when i am trying to create an object in it's own class?

package inheritance;  

public class SingleInheritance {

//  SingleInheritance obj=new SingleInheritance();     Why does this line is not giving any error when I am creating a class's object in it's own class

    public static void main(String[] args) {
        Plumber rahul=new Plumber();   
        
        }

}
package inheritance;

class Plumber{
    
    Plumber ganesh=new Plumber();  
        // while  this one is giving the Whosebugerror.
    }

当我在它自己的 class 中创建 SingleInheritance class 的对象时它不会抛出任何错误,但是当我在另一个 class 中做同样的事情时抛出错误。 我知道在它自己的 class 中创建对象是愚蠢的,但是当我试图做其他事情时发生了这种情况。我需要对发生的事情进行解释。

您的代码存在的问题是递归创建了您的 class Plumber 对象,并且没有终止它的条件。

让我们看看您的 class Plumber 的内容及其实例化。

class Plumber
{
   Plumber obj = new Plumber();
}

您认为这对创建 new Plumber() 对象有什么作用。 它将实例化一个 new Plumber()obj,这将在 return 中创建另一个 new Plumber()obj.obj,依此类推..

您当然可以将一个对象保留为管道工 class,但是当您想要实际初始化它时,您需要有一个特定的流程。

class Plumber
{
   Plumber obj;
   public Plumber()
   {
      if(/*condition*/)
      {
         obj = new Plumber();
      }
   }

   // You can also use some methods to do so
   public InstantiateObj()
   {
      obj = new Plumber();
   }
}

这是因为您没有实例化 SingleInheritance class。 代码

public class SingleInheritance {

    SingleInheritance obj=new SingleInheritance(); 

    public static void main(String[] args) {
        Plumber rahul=new Plumber();   
    }
}

没有创建 SingleInheritance 的新实例,因为 main 是一个静态函数。

如果您将代码更改为:

public class SingleInheritance {

    SingleInheritance obj=new SingleInheritance(); 

    public static void main(String[] args) {
        SingleInheritance rahul=new SingleInheritance();   
    }
}

您将获得相同的 Whosebug 异常,因为现在 main 将实例化 SingleInheritance。你得到 Whosebug 的原因是 new Plumber() 像其他答案解释的那样调用它自己的构造函数。