【问题标题】:Why is it showing stackoverflowerror when i am trying to create an object in it's own class?为什么当我尝试在它自己的类中创建一个对象时它显示stackoverflowerror?
【发布时间】:2020-12-21 05:58:53
【问题描述】:
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 stackoverflowerror.
    }

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

【问题讨论】:

    标签: java recursion exception stack-overflow


    【解决方案1】:

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

    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();   
        }
    }
    

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

    【讨论】:

      【解决方案2】:

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

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

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

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

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

      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();
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-13
        • 2020-10-01
        • 2010-12-19
        • 1970-01-01
        • 2012-05-27
        • 1970-01-01
        • 1970-01-01
        • 2021-11-19
        相关资源
        最近更新 更多