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

前端 未结 6 1553
遥遥无期
遥遥无期 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 would have to make the variables public class variables instead of method variables, thereby increasing the scope and visiblity of the variables. Like so:

    public class ActionClass {
    {
        public string MyPublicVariable = "woot";
    
        @Override
        public void actionPerformed(ActionEvent e) {
    
    
            ...
        }
    }
    

    A more popular/recommended way to do this is to use a getter/setter instead of making the variable explicitly public. You would access a private variable through public methods like so:

    public class ActionClass {
    {
        @Override
        public void actionPerformed(ActionEvent e) {
    
            private string MyPublicVariable = "woot";
    
            public void setMyString(string newString){
                MyPublicVariable = newString;
            }
    
            public string getMyString(){
                return MyPublicVariable;
            }
        }
    }
    

    This way, you have more control over what your variables are set to.

提交回复
热议问题