Search code examples
javarecursionexceptionstack-overflow

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 stackoverflowerror.
    }

It does not throws any error when I create the object of SingleInheritance class in it's own class but throws an error while I do the same thing in another class .error I know It is silly to create object in it's own class but this happened when I was trying to do something else. I need an explanation to what is happening .


Solution

  • The issue with your code is that there is recursively creation of your class Plumber objects and no condition that will terminate it.

    Let us see the contents of your class Plumber and their instantiation.

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

    What do you think this does on creating a new Plumber() object. It will instantiate a new Plumber() to obj, which will in return create another new Plumber() to obj.obj, and so on ..

    You sure can keep an object a Plumber in same class, but you need to have a specific flow when you want to actually initialize it.

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