InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
What is circular dependency?
Circular dependency happens when two or more things depend on each other directly or indirectly, creating a loop that can cause problems.
Example:
Imagine there are two files in a program:
1: File A needs something from File B
2: File B also needs something from File A
Because both files are waiting for each other, it creates a circle, and the program might not work properly.
In short:
Circular dependency is like two friends who each refuse to start a task until the other does, so nothing ever gets done.
Real-Time Example: Student and Course
Suppose you are designing a school system where:
1: Each Student is enrolled in a Course.
2: Each Course keeps track of the Student as a representative.
If both classes directly reference each other in their fields, you create a circular dependency.
Student.java
public class Student {
private String name;
private Course course;
// Student is enrolled in a Course
public Student(String name, Course course) {
this.name = name;
this.course = course;
}
}
Course.java
public class Course {
private String title;
private Student representative;
// Course has a Student as representative
public Course(String title, Student representative) {
this.title = title;
this.representative = representative;
}
}
What happens?
1: When you try to create a Student, you need a Course.
2: When you try to create a Course, you need a Student.
3: This can make it difficult to initialize objects without running into issues, because each one requires the other to exist first.
How to avoid this?
1: Use setter methods to assign one property after initial creation.
2: Use interfaces or design patterns to decouple the classes.