Java cyclic dependency

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.