0

Instance variables go on stack and objects go on heap and object references go on stack. Right? But what if an instance variable was a reference to an object? Like var c:

class clony implements Cloneable {

    clony c = new clony();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class tst2 {

    public static void main(String[] args) throws CloneNotSupportedException {
        clony j1 = new clony();
    }
}

And if it goes on heap why it throws and stack overflow error?

trincot
  • 317,000
  • 35
  • 244
  • 286
mike
  • 45
  • 5

3 Answers3

2

Your reference c is a field of the class clony. That means the reference will be stored on the heap inside the memory region that is allocated for the clony object.

And your program throws a stack overflow exception since clony infinitely constructs itself: Inside the constructor of clony you create a new clony object and assign it to field c: Which will then do the same thing again and again.

Matthias247
  • 9,836
  • 1
  • 20
  • 29
0

This is because the stack is also used to keep track of method calls. Every time you call a method (the class's default constructor, in this case), certain information is added to the stack for that purpose. When you have infinite recursion (as you have with your constructor), that fills up the stack PDQ.

Joe C
  • 15,324
  • 8
  • 38
  • 50
0

I think this:

clony c = new clony();

Gives you the exception.

new clony() also has clony c = new clony() 

inside... and it goes to infinity.

By the way, classes should be named with capital letter at the beginning.

MicD
  • 197
  • 2
  • 11