Java object dependency
Address: http://leihuang.org/2014/11/13/Cycular-Dependency/
Suppose we have A class A, which contains an object of B, and Class B also contains an object of. At this time, StackOverflowError will occur no matter which class you instantiate. This is a java object loop dependency problem. Similar to chicken and egg problems.
First, let's take a look at the following error code and analyze the 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(10) ; } 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 reported by the code above, because when you create a Chicken object, you also need an Egg object, and an Egg object also needs a Chicken object, in this way, the stack overflow error occurs during the loop.
So how can we solve this problem? We can write a ChickenProxy proxy for the Chicken, so that Egg does not include Chicken but the ChickenProxy of the proxy class, so that a third party is used to solve the circular 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(10) ; } 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; }}
15:41:41
Brave, Happy, Thanksgiving!