Original address: http://leihuang.net/2014/11/13/Cycular-Dependency/
Suppose we have a Class A, which contains a B object, and Class B also contains an A object. At this point, no matter which class you instantiate, there will be a stackoverflowerror error, which is the Java object Circular dependency problem. Similar to chicken and egg problems.
First we look at the error code below and analyze its error.
Public class cyclicdependencies { Public Static void Main(String args[]){ Chicken C = New Chicken() ; //egg e = new Egg (); }}class Chicken{ Private Egg e ; Private int Age ; Public Chicken(){ e = New Egg() ; Setage(Ten) ; } Public int Getage() { return Age; } Public void Setage(int Age) { This. Age = Age; }}class Egg{ Private Chicken Chicken ; Private int Weight ; Public Egg(){ Chicken = New Chicken() ; Setweight(1) ; } Public int Getweight() { return Weight; } Public void Setweight(int Weight) { This.Weight = Weight; }}
Exception in thread "main" java.lang.StackOverflowError
This is an error in the above code, because when you create a chicken object, you also need an egg object, and an egg object needs a chicken object, so the stack overflow error occurs when the loop continues.
So how to solve this problem? We can write a proxy class chickenproxy for chicken so that the egg contains no longer chicken but the proxy class Chickenproxy, which utilizes a third party to solve the cyclic dependency problem. The code is as follows.
Public class cyclicdependencies { Public Static void Main(String args[]){ Chicken C = New Chicken() ; Egg e = New Egg(C) ; System. out.println(C.Getage()); System. out.println(e.Getweight()); }}Interface Chickenproxy{ int Getage(); void Setage(int Age) ;}class Chicken Implements Chickenproxy{ Private Egg e ; Private int Age ; Public Chicken(){ e = New Egg( This) ; Setage(Ten) ; } Public int Getage() { return Age; } Public void Setage(int Age) { This. Age = Age; }}class Egg{ Private Chickenproxy Chicken ; Private int Weight ; Public Egg(Chicken C){ Chicken = C ; Setweight(1) ; } Public int Getweight() { return Weight; } Public void Setweight(int Weight) { This.Weight = Weight; }}
2014-11-13 15:41:41
Brave,happy,thanksgiving!
Java Object Cyclic dependency problem