如果在 java 中以类的非静态方法创建对象会发生什么


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"
    }
}

所以我的问题是在 show(( 中创建一个对象,即"d1",它必须有自己的一组数据成员,并且必须为其 show(( 方法分配一个新的堆栈,作为回报,它应该创建一个新对象,因此循环应该继续并且发生堆栈溢出?但这工作得很好??

Data d1=new Data(); 

此语句本身不会为 show(( 分配新的堆栈。 show(( 的堆栈仅在被调用时才分配,例如,当它在 main 中被调用时。

您的show()方法只会被调用一次。 创建Data实例时不会调用show()。所以,你不会得到SOE。

尝试此代码以获取 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"
    }
}

最新更新