I\'m making a cookie clicker clone in java to practice my java skills and I have a small problem, I have variables that are declared in the main method that I want to access
You can pass main class instance reference to another class instance, or register callback. For the first way
Class MainClass {
private int mValue;
public void init() {
AnotherClass cla = new AnotherClass(this);
}
public void setValue(int value) {mValue = value;}
public int getValue(){return mValue;}
}
Class AnotherClass {
private MainClass mMain;
public AnotherClass(MainClass ref) {
mMain = ref;
}
public void controlValue() {
if (mMain != null) {
mMain.setValue(1);
mMain.getValue();
}
}
}
For the second way 1. declare an interface 2. implement this interface in main class 3. register this implementation to another class. 4. get and set value in another class.
public interface ClassListener {
public void setValue(int value);
public int getValue();
}
public class MainClass implements ClassListener{
private int mValue;
public void registerListener() {
AnotherClass cla = new AnotherClass();
cla.registerListener(this);
}
@Override
public void setValue(int value) {
// TODO Auto-generated method stub
mValue = value;
}
@Override
public int getValue() {
// TODO Auto-generated method stub
return mValue;
}
}
public class AnotherClass{
private ClassListener mListener;
public void registerListener(ClassListener listener) {
mListener = listener;
}
public void controlValue() {
if (mListener != null) {
int value = mListener.getValue();
mListener.setValue(++value);
}
}
}