Lets say I have 3 Classes: A
, Data
, and B
I pass a variable from class A
which sets that passed variable to a private variable in class Data
.
Then in class B
, I want to call that specific variable which has been changed.
So I do
Data data = new Data();
data.getVariable();
It will then return null, since in class Data
I initialize variables to nothing (ex: int v;
), and I think that class B
is initializing a brand new class and resetting the values to default, but I don't know how to fix this.
I know that the variable is setting properly because in class A
if I do data.getVariable()
it will print the variable that was set.
Class A
:
Data data = new Data();
int d = 1;
data.setVariable(d);
Class Data
:
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
Class B
:
Data data = new Data();
private int v;
v = data.getVariable();
System.out.println(v);
This will print out 0 instead of the actual value
When you instantiate a Data
object in class A, and instantiate another Data
object in class B, they are two different instances of the Data
class. They both instantiate d
to 0 by default. You then call setVariable
on the instance in class A and pass it the value of 1; but the instance in class B remains in 0. In order to change the value of the instance in class B, you would need to call setVariable
on the instance in class B.
What it seems like you're looking for is a static member. Static members are the same across all instances of the same class. Just put the static
keyword before the method(s) or field(s) that you want to use it. Static members and fields are typically accessed using the name of the class in which they are declared (i.e. MyClass.doMethod()
). For example:
Class Data (updated):
private static int b;
public static void setVariable(int s)
{
b = s;
}
public static int getVariable()
{
return b;
}
Class A:
Data.setVariable(d);
Class B:
v = Data.getVariable();
System.out.println(v);