Friday, June 24, 2011

Compiling cyclic dependency in Java

I recently cam across– If there is cyclic dependency between classes A, B and C. How do you go about compiling them in java? Apparently, that came up in an interview for someone.
Well, I don’t know what kind of dependency that person had in mind when asking this question – But I had not heard of anything being needed to compile in cases of cyclic dependencies as described below. Check out the code below – At least the current version of Java is clever enough that  you need to do nothing special to compile it.
Maybe this was a problem in old versions of Java and interviewers are still stuck looking for answers that are incorrect. Check out the demo code below -
package test;
class A{
  A(){
    new B();
  }
}

package test;
class B{
  B(){
    new C();
  }
}

package test;
class C{
  C(){
    new A();
  }
}

Of course, trying to instantiate any of the above classes would lead to a StackOverflowError.

No comments:

Post a Comment

Chitika