public class MyClass {
public static void main(String[] args) {
//How to initialize an instance of class One or class Two
}
}
class One{
Two t;
One(Two t){
this.t = t;
}
}
class Two{
One o;
Two(One o){
this.o = o;
}
}
我只是想知道是否可以初始化一级或二级的实例?如果不可能,有没有人在他们的项目中遇到类似的情况?有没有办法解决这种相互依赖性问题?
答案 0 :(得分:5)
实际上你可以简单地实例化其中任何一个参考另一个类为null
例如,你可以写
One o = new One(null);
Two t = new Two(o);
o.t = t; // or use a setter
答案 1 :(得分:1)
在每个对象中为另一个类型创建一个setter,并从构造函数中删除它们。
public class One {
private Two two;
public void setTwo(Two two) {
this.two = two;
}
}
和
public class Two {
private One one;
public void setOne(One one) {
this.one = one;
}
}
现在
public static void main(String[] args) {
One one = new One();
Two two = new Two();
one.setTwo(two);
two.setOne(one);
}
这是最简单的方法,但更好的问题是:为什么你需要这个呢?
答案 2 :(得分:1)
如果你有两个相互依赖的类,一个简单的解决方案是只在其中一个中创建两个引用,如下所示:
public class A {
private B b;
public A(B b) {
this.b = b;
b.setA(this);
}
...
}
public class B {
private A a;
public B() {
}
public void setA(A a) {
this.a = a;
}
...
}
你可以将它们实例化如下:
B b = new B(); // Here a doesn't yet exists so is correct
// that a is not referenced from b
A a = new A(b); // The constructor of A create both references
// from a to b and from b to a
// Here a references b and viceversa