How do I access variables from the main class from another class (java)?

前端 未结 6 1510
遥遥无期
遥遥无期 2020-12-11 09:06

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

6条回答
  •  执念已碎
    2020-12-11 09:46

    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);
            }
        }
    }
    

提交回复
热议问题