gpt4 book ai didi

java - 对象的递归实例化?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:26:07 26 4
gpt4 key购买 nike

public class ran {

ran obj1 = new ran();//will this create a recursive instantiating of objects??
public String s = null;

public static void main(String[] args) {

ran obj2 = new ran();
obj2.s = "main";
obj2.obj1.s = "secondary";
System.out.println(obj2.obj1.s);

}

}

the above code gives a stack overflow error..so what is exactlyhappening here? the obj2 is instantiated ,with it is instantiatedobj1,and obj1 then again instantiates another object of ran class anda chain is formed??

if so then is there a workaround without making obj1 as static ?

应伙伴气垫船的特殊要求..

编辑问题=我试图复制一个自引用结构,就像在链表中的 c/c++ 中使用的那样

最佳答案

看起来您正在尝试构建类似列表的结构。

通常的模式是:

class Ran {
Ran obj1 = null;
Ran() { initializer } }
void setObj1(Ran obj1) { this.obj1 = obj1; }
}

如果不是,那么你应该考虑在Ran类中构造递归对象的数据,而不是构造递归对象。

关于java - 对象的递归实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21205321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com