How to share data between separate classes in Java

后端 未结 4 973
面向向阳花
面向向阳花 2020-12-29 12:44

What is the best way to share data between separate classes in Java? I have a bunch of variables that are used by different classes in separate files in different ways. Let

4条回答
  •  北海茫月
    2020-12-29 13:06

    I am having a hard time seeing what your problem is -- why don't you want to pass x an y as a parameter?

    Oh, well. Assuming you don't, I don't see a need for a new container class. Do it this way:

    public class SubClass1a() {  // in its own separate file
        public void doA(Top_Level_Class caller, int p, int q, int r){
           // do something that requires x,y and p, q, r
           // **to get x use the expression term caller.getX() and caller.getY()**
        }
    }
    

    Of course you need to add the public getter methods getX() and getY() to Top_Level_Class.

    If you do not want SubClass1a to be dependent on Top_Level_Class then you could create an interface that provides access to the variables.

提交回复
热议问题