Circular dependency Java classes

Circular dependency in java is a condition where two object are depends on each other and it goes to infinite loop and finally it throws java.lang.StackOverflowError. Please see java class below:

package com.javahonk;

public class CircularDependencies {

    Circular circular;

    public CircularDependencies() {
        circular = new Circular();
    }

    public static void main(String[] args) {
        CircularDependencies cDependencies = 
            new CircularDependencies();
        System.out.println(cDependencies);
    }

}

class Circular {

    CircularDependencies cDependencies;

    public Circular() {
        cDependencies = new CircularDependencies();
    }

}

Output: Circular dependency Java classes Solution: Create object separately and set its value as below:

package com.javahonk;

public class CircularDependencies {

    Circular circular;  

    public void setCircular(Circular circular) {
        this.circular = circular;
    }

    public CircularDependencies() {
        circular = new Circular();
    }

    public static void main(String[] args) {
        
        Circular circular = new Circular();
        CircularDependencies cDependencies = 
            new CircularDependencies();
        
        circular.setcDependencies(cDependencies);
        cDependencies.setCircular(circular);        
        
    }

}

class Circular {

    CircularDependencies cDependencies;

    public CircularDependencies getcDependencies() {
        return cDependencies;
    }

    public void setcDependencies(CircularDependencies cDependencies) {
        this.cDependencies = cDependencies;
    }
    

}

Leave a Reply

Your email address will not be published. Required fields are marked *