Om Kumar
Om Kumar

Reputation: 21

How to create two objects that hold a reference to eachother?

class A {
    B ob1 = new B();
}

class B {
    A ob2 = new A();
}

class C {
    A a = new A();
   // I am getting a StackOverflowException here 
}

I am getting a StackOverflowException on the line I commented on. How can I solve this?

Upvotes: 1

Views: 1265

Answers (2)

Pshemo
Pshemo

Reputation: 124265

Problem with your approach is that when you create instance of A, this instance have to create instance of B which also have to create instance of A which creates instance of B... and so on until stack will overflow.


Probably most intuitive way would to solve this problem with getters/setters like

class A{
    private B b;
    public void setB(B b) { this.b = b; }
    public B getB() { return b; }
}

class B{
    private A a;
    public void setA(A a) { this.a = a; }
    public A getA() { return a; }
}

class Demo {
    public static void main(final String[] args) throws Exception {
        A a = new A();
        B b = new B();
        //let them see each other
        a.setB(b);
        b.setA(a);
    }
}

Upvotes: 7

Martin Dinov
Martin Dinov

Reputation: 8825

If you want the B object to hold a reference to the A object that created it, you want something like this:

class A {
    B ob1 = new B(this);
}

class B {
    A a;

    public B(A a) {
        this.a = a;
    }

}

This will not result in a StackOverflow and B will know about A and A will know about B. What you were doing is creating an instance of A which created an instance of B which created an instance of A which created...

Upvotes: 3

Related Questions