I have two java class files. Each of them has methods the other one uses.
public class class1{
class2 c2 = new class2();
m1(){
c2.ma();
What actually happens is that you create an instance of Class1
in the constructor,
Class2
in the constructor,
Class1
in the constructor,
Class2
in the constructor,
Your constructors are recursingly creating instances, causing the call stack to flood, resulting in a StackOverflowError
.
I assume you want an instance of Class1
to hold a reference to an instance of Class2
and vice versa?
In that case, you can just do this:
public class Class1 {
private Class2 c2;
public Class1() {
this.c2 = new Class2(this);
}
}
public class Class2 {
private Class1 c1;
public Class2(Class1 class1) {
this.c1 = class1;
}
}
Cyclic aggregations like this are often a sign of a bad design; but there are situations where it is perfectly valid, or at least reflects reality.