You have two classes, ClassA and ClassB, each dependent on the other. Both classes' constructors require the other class as a parameter. How would you resolve this circular dependency in Java?

A circular dependency occurs when two classes depend on each other for creation or operation. If both classes require each other through constructor injection, object creation becomes impossible because each object needs the other to exist first. To resolve this, the dependency should be delayed using setter injection, factory methods, dependency inversion, or redesigning the relationship to reduce coupling.

Key Points: • Constructor-based circular dependencies prevent object creation because neither object can be instantiated first. • Setter injection or factory methods allow objects to be created independently and wired together afterward. • Excessive circular dependencies often indicate a design issue and can sometimes be eliminated by introducing an interface or a third coordinating class.

Example: Suppose ClassA handles order processing and ClassB handles notifications. If both classes directly depend on each other through constructors, object creation fails. Instead, create both objects first and then inject the dependencies using setter methods.

Code Example:

class ClassA {

    private ClassB classB;

    public void setClassB(
            ClassB classB) {

        this.classB = classB;
    }
}

class ClassB {

    private ClassA classA;

    public void setClassA(
            ClassA classA) {

        this.classA = classA;
    }
}

public class Main {

    public static void main(String[] args) {

        ClassA a = new ClassA();
        ClassB b = new ClassB();

        a.setClassB(b);
        b.setClassA(a);
    }
}

Interview Tip: A concise interview answer is: Constructor-based circular dependencies can be resolved by using setter injection, factory methods, or redesigning the classes to reduce coupling. The most common approach is to create both objects independently and inject the dependencies afterward, breaking the circular construction chain.