Why am I getting a StackOverflowError exception in my constructor

public class Cloning { Cloning c=new Cloning(); public static void main(String[] args) { Cloning c=new Cloning(); c.print(); } public void print(){ System.out.println("I am in print"); } } 

In the above code, I have a simple class and an instance of the class, I also have a local instance with the same name. When running the above code, I get the following exception:

 Exception in thread "main" java.lang.StackOverflowError at com.java8.Cloning.<init>(Cloning.java:6) 
+6
source share
3 answers

Your main method creates an instance of Cloning ( Cloning c=new Cloning(); ), which causes the instance variable c be initialized ( Cloning c=new Cloning(); ), which creates another instance of Cloning and so on ...

You have an infinite chain of constructor calls, which leads to a StackOverflowError .

In the above code, I have a simple class and an instance of the class

You do not have an instance of the class. You have an instance level instance. If you want an instance of the class, change

 Cloning c=new Cloning(); 

to

 static Cloning c=new Cloning(); 
+23
source

You create an instance of the Cloning class each time Cloning is built, which causes recursion when instantiating.

+7
source

Didn't you want to write static Cloning c = new Cloning(); outside main or c = new Cloning(); inside main ?

Otherwise, you will get a new instance of c every time you start, which will result in a StackOverflowError .

Currently creating local c in Cloning c = new Cloning(); (which shadows the c field) disables it all.

+7
source

All Articles