-3
class Data {
    int x = 20; // instance variable

    public void show() // non-static method
    {
        Data d1 = new Data(); // object of same class Data
        int x = 10;
        System.out.println(x); // local x
        System.out.println(d1.x);// instance variable x
    }

    public static void main(String... args) {
        Data d = new Data();
        d.show(); // "10 20"
    }
}

So my question when an object is created in show() namely 'd1' , it must have its own set of data members and must have allocated a new stack for its show() method , which in return should create a new object and thus the cycle should go on and stack-overflow occurs?? But this is working perfectly fine??

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Gagan
  • 103
  • 1
  • 1
  • 7

2 Answers2

2
Data d1=new Data(); 

this statement itself will not allocate a new stack for show(). show()'s stack is allocated only when it gets called, for example, when it gets called in main.

liusy182
  • 205
  • 1
  • 7
1

Your show() method will be called only once. show() is NOT called when an instance of Data is being created. So, you will not get SOE.

Try this code to get SOE :P

class Data {
    int x = 20; // instance variable

    Data() {
        show(); // This will cause SOE
    }
    public void show() // non-static method
    {
        Data d1 = new Data(); // object of same class Data
        int x = 10;
        System.out.println(x); // local x
        System.out.println(d1.x);// instance variable x
    }

    public static void main(String... args) {
        Data d = new Data();
        d.show(); // "10 20"
    }
}
TheLostMind
  • 35,966
  • 12
  • 68
  • 104