Global variables in Java

后端 未结 24 1858
青春惊慌失措
青春惊慌失措 2020-11-22 11:56

How do you define Global variables in Java ?

24条回答
  •  隐瞒了意图╮
    2020-11-22 12:39

    Understanding the problem

    I consider the qualification of global variable as a variable that could be accessed and changed anywhere in the code without caring about static/instance call or passing any reference from one class to another.

    Usually if you have class A

    public class A {
        private int myVar;
    
        public A(int myVar) {
            this.myVar = myVar;
        }
    
        public int getMyVar() {
            return myVar;
        }
    
        public void setMyVar(int mewVar) {
            this.myVar = newVar;
        }
    }
    

    and want to access and update myvar in a class B,

    public class B{
    
        private A a;
    
        public void passA(A a){
            this.a = a;
        }
    
        public void changeMyVar(int newVar){
            a.setMyvar(newVar);
        }
    }
    

    you will need to have a reference of an instance of the class A and update the value in the class B like this:

    int initialValue = 2;
    int newValue = 3;
    A a = new A(initialValue);
    B b = new B();
    b.passA(a);
    b.changeMyVar(newValue);
    assertEquals(a.getMyVar(),newValue); // true
    

    Solution

    So my solution to this, (even if i'm not sure if it's a good practice), is to use a singleton:

    
    public class Globals {
        private static Globals globalsInstance = new Globals();
    
        public static Globals getInstance() {
            return globalsInstance;
        }
    
        private int myVar = 2;
    
        private Globals() {
        }
    
        public int getMyVar() {
            return myVar;
        }
    
        public void setMyVar(int myVar) {
            this.myVar = myVar;
        }
    }
    

    Now you can get the Global unique instance anywhere with:

    Globals globals = Globals.getInstance();
    // and read and write to myVar with the getter and setter like 
    int myVar = globals.getMyVar();
    global.setMyVar(3);
    

提交回复
热议问题