Recently saw a problem: if there are two classes A and B,a class with a B object B,b class has a object A, then how to solve the interdependence of the two classes?
Example code 1
public class test{public static void Main (string[] args) {b TESTB = new B ();}} Class A{public B b;public A () {b = new B ();} public void Printb () {System.out.println ("Ab"); B.printa ();} public void PrintA () {System.out.println ("AA");} }class b{public a a;public B () {a = new A ();} public void Printb () {System.out.println ("BB"); A.printa ();} public void PrintA () {A.printa ();} }
As you can see in the constructor of Class A, new is an object of B, and in the construction method of Class B, the object of a is new.
If we run the class at this point, we will report the following error:
Exception in thread "main" Java.lang.StackOverflowError
The problem arises because of a cyclic dependency between Class A and category B.
Java cyclic dependency