如果在 java 中 class 的非静态方法中创建一个对象会发生什么?
What would happen if an object is created in non-static method of class in 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() 方法分配一个新堆栈,这在 return 应该创建一个新对象,因此循环应该继续并发生堆栈溢出??
但这工作得很好??
您的 show()
方法只会被调用一次。 show()
在创建 Data
的实例时不会被调用。所以,你不会得到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"
}
}
Data d1=new Data();
此语句本身不会为 show() 分配新堆栈。 show()的栈只有在被调用时才分配,例如在main中被调用时。
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() 方法分配一个新堆栈,这在 return 应该创建一个新对象,因此循环应该继续并发生堆栈溢出?? 但这工作得很好??
您的 show()
方法只会被调用一次。 show()
在创建 Data
的实例时不会被调用。所以,你不会得到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"
}
}
Data d1=new Data();
此语句本身不会为 show() 分配新堆栈。 show()的栈只有在被调用时才分配,例如在main中被调用时。