6
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 a class level instance, I also have a local instance with the same name. When running the above code I get below exception :

Exception in thread "main" java.lang.StackOverflowError
    at com.java8.Cloning.<init>(Cloning.java:6)
Raedwald
  • 46,613
  • 43
  • 151
  • 237
Nitish Singla
  • 165
  • 1
  • 6
  • 1
    This looks like an attempt to implement a Singleton pattern. There are a number of ways of doing that. Do a search for Java Singleton and you'll find many examples. – Darrel Hoffman Mar 07 '16 at 14:25
  • 1
    Nice Q to ask on StackOverflow! You should add "no pun intended" ;). – Astrogator Mar 07 '16 at 16:14

3 Answers3

24

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

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

In the above code I have a simple class and a class level instance

You don't have a class level instance. You have an instance level instance. If you want a class level instance, change

Cloning c=new Cloning();

to

static Cloning c=new Cloning();
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Actually I *think* the culprit is the creation of the non-`static` `Cloning` instance outside `main`. – Bathsheba Mar 07 '16 at 13:23
  • 2
    @Bathsheba Well, the original instance is created by the main method. Without that instantiation, no instance variable would be initialized, so the chain of infinite constructor calls wouldn't start. I agree that the bug is probably in not declaring the instance variable as static (which seems to be what the OP wanted). – Eran Mar 07 '16 at 13:29
  • 1
    Also not sure why we're instantiating `Cloning` both inside *and* outside `main()`. Surely only one of them is needed. – Darrel Hoffman Mar 07 '16 at 14:24
7

You instantiate the class Cloning every time Cloning is constructed, which causes a recursion on instantiations.

Robert Bräutigam
  • 7,514
  • 1
  • 20
  • 38
7

Didn't you mean to write static Cloning c = new Cloning(); outside main, or c = new Cloning(); within main instead?

Otherwise, you'll get a new instance of c each time this is run, which will cause a StackOverflowError.

Currently the creation of the local c in Cloning c = new Cloning(); (which shadows the field c) kicks the whole thing off.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Bathsheba
  • 231,907
  • 34
  • 361
  • 483