Circular dependency in java classes

后端 未结 5 1920
误落风尘
误落风尘 2020-11-28 09:23

I have the following classes.

public class B 
{
    public A a;

    public B()
    {
        a= new A();
        System.out.println(\"Creating B\");
    }
         


        
5条回答
  •  温柔的废话
    2020-11-28 10:00

    The constructor of your class A calls the constructor of class B. The constructor of class B calls the constructor of class A. You have an infinite recursion call, that's why you end up having a StackOverflowError.

    Java supports having circular dependencies between classes, the problem here is only related to constructors calling each others.

    You can try with something like:

    A a = new A();
    B b = new B();
    
    a.setB(b);
    b.setA(a);
    

提交回复
热议问题