I have a small problem with doing calculations in one java class and trying to refer to the varibles in another class. I have written a GUI program that performs certain calculations and then when a button is pressed, the values obtained are saved as variables in another Java class ( called Calculations.class) . What I need to know is how can I access these variables again from another class so they can be used in further calculations.

Dani AI

Generated

A few practical patterns that keep the design clean and make the calculated values easy to reuse:

Keep calculations out of global mutable fields. Either make the calculator stateless (a method that computes and returns a result) or make a small model object that holds results with private fields and public getters. That gives you clear ownership of the data and avoids accidental overwrites. ′s approach of creating an instance will work — but only if the same instance (or its returned result) is passed around; creating new instances each time loses previous state. was right to flag design as the deciding factor: pick a pattern that fits whether the values are transient results or persistent application state.

Example (immutable result + single-call compute):

public final class CalcResult {
    private final double total;
    public CalcResult(double total) { this.total = total; }
    public double getTotal() { return total; }
}

public class Calculations {
    public static CalcResult compute(double[] inputs) {
        double sum = 0;
        for (double v : inputs) sum += v;
        return new CalcResult(sum);
    }
}

Call the compute method on button press, keep the returned CalcResult reference in your controller, or pass it to whichever class needs further processing. That avoids public fields and makes testing straightforward.

Troubleshooting and cautions: if the GUI triggers long computations, run them off the Swing Event Dispatch Thread (use SwingWorker). Avoid static mutable fields for shared state — they complicate concurrency and unit tests. If many parts of the app must react when values change, use a single model instance with listener support (PropertyChangeSupport) so components get notified instead of polling or relying on ad hoc shared variables.

Recommended Answers

All 2 Replies

It depends on how your classes are designed. Can you use inheritance or packages to allow access? Otherwise you're either going to be hosed, or you have to make the members public.

you can simply make an object of the class you want to use ... like this

public class1{

      WantedVariableClass wvc = new WantedVariableClass();
   
      //now you can access the variables like this
      wvc.variable1 = 10 + 90;
      wvc.variable2 = 10;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.