Java classes reference each other

前端 未结 3 971
执笔经年
执笔经年 2021-01-17 22:18

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(); 
            


        
3条回答
  •  感情败类
    2021-01-17 22:57

    What actually happens is that you create an instance of Class1 in the constructor,

    • which creates an instance of Class2 in the constructor,
      • which creates an instance of Class1 in the constructor,
        • which creates an instance of Class2 in the constructor,
          • et cetera.

    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.

提交回复
热议问题