Java classes reference each other

前端 未结 3 969
执笔经年
执笔经年 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:55

    Is there some way to have the classes refer to each other or do I have no choice but to transfer all of my methods into a single class?

    In my opinion, cyclic references are a code-smell. See this answer for an explanation. Take special note of the point about cognitive load.

    The solution is to have one class depend on the other and delegate the calls to the other class :

    public class class1{
        class2 c2 = new class2(); 
        m1(){
            c2.ma(); 
            m2();
        }
        m2(){}
    }
    
    public class class2{
        ma(){}
    }
    

    This way, you are not really transferring all the methods to one class but just composing class2 into class1. Other classes that were depending on class1 and class2 only have to depend on class1 instead.

提交回复
热议问题