Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to share data between separate classes in Java
    primarykey
    data
    text
    <p>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 me try to illustrate a simplified version of my problem:</p> <p>This was my code before:</p> <pre><code>public class Top_Level_Class(){ int x, y; // gets user input which changes x, y; public void main(){ int p, q, r, s; // compute p, q, r, s doA(p,q,r); doB(q,r,s); } public void doA(int p, int q, int r){ // do something that requires x,y and p, q, r } public void doB(int q, int r, int s){ // does something else that requires x, y and q, r, s } } </code></pre> <p>Now it looks something like this:</p> <pre><code>public class Top_Level_Class(){ int x, y; SomeClass1a a = new SomeClass1a(); SomeClass1a b = new SomeClass1b(); // gets user input which changes x, y; public void main(){ int p, q, r, s; // compute p, q, r, s a.doA(p,q,r); b.doB(q,r,s); } public class SomeClass1a() { // in its own separate file public void doA(int p, int q, int r){ // do something that requires x,y and p, q, r } } public class SomeClass1b() { // in its own separate file public void doB(int q, int r, int s){ // does something else that requires x, y and q, r, s } } </code></pre> <p>So anyway, should I pass x and y each time (where x,y are variables stored in the helper class func) ?</p> <pre><code> a.set(x,y); a.doA(p,q,r); </code></pre> <p>My idea was to have a special container class where x and y are held. The top level class would have an instance of the container class and change x,y using the set methods. </p> <pre><code>// in the top level class: Container c = new Container(x,y); a.setContainer(c); b.setContainer(c); </code></pre> <p>My helper classes would also have an instance of the container and it would point to the same instance as in the top level. That way they access the same x,y as in the top level.</p> <p>I would like to know if I should</p> <ul> <li>Use the container class</li> <li>Load x,y each time into the subclasses</li> <li>?? Some better method ??</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload