Set and get a static variable from two different classes in Java

Suppose I have 3 classes: A, DataandB

I am passing a variable from a class Athat sets the passed variable to a private variable in the class Data.

Then in the class BI want to call this variable that has been changed.

So i do

Data data = new Data();
data.getVariable();

Then it will return null, since in the class DataI initialize the variables with nothing (ex:) int v;, and I think the class Binitializes the new class and returns the default values, but I do not know how to fix it.

I know that the variable is configured correctly, because in the class A, if I do data.getVariable(), it will output the given variable.

Grade A:

Data data = new Data();
int d = 1;
data.setVariable(d);

Grade Data:

private static int b;

public void setVariable(int s)
{
    b = s;
}

public int getVariable()
{
    return b;
}

Grade B:

Data data = new Data();
private int v; 

v = data.getVariable();
System.out.println(v);

0

+5
2

Data A Data B, Data. d 0. setVariable A 1; B 0. B, setVariable B.

, . . static , (), . , , (.. MyClass.doMethod()). :

():

private static int b;

public static void setVariable(int s)
{
    b = s;
}

public static int getVariable()
{
    return b;
}

A:

Data.setVariable(d);

B:

v = Data.getVariable();
System.out.println(v);
+10

- , static b, , .

, . , :

    public class Demo {
        public static void main(String[] args) {
            A a = new A();
            B b = new B();
            a.doWhatever();
            b.doSomethingElse();
        }
    }
    class Data {
        private static int b;

        public void setVariable(int s)
        {
            b = s;
        }

        public int getVariable()
        {
            return b;
        }
    }
    class A {
        public void doWhatever() {
            Data data = new Data();
            int d = 1;
            data.setVariable(d);
        }
    }

    class B {
        Data data = new Data();
        private int v; 
        public void doSomethingElse() {
            v = data.getVariable();
            System.out.println(v);
        }
    }
+1

All Articles